I frequently run into problems of this form and haven’t found a good solution yet:
Assume we have two database tables representing an e-commerce system.
userData (userId, name, ...) orderData (orderId, userId, orderType, createDate, ...)
For all users in the system, select their user information, their most recent order information with type = ‘1’, and their most recent order information with type = ‘2’. I want to do this in one query. Here is an example result:
(userId, name, ..., orderId1, orderType1, createDate1, ..., orderId2, orderType2, createDate2, ...) (101, 'Bob', ..., 472, '1', '4/25/2008', ..., 382, '2', '3/2/2008', ...)
This should work, you’ll have to adjust the table / column names:
Denormalizing your data might also be a good idea. This type of thing will be fairly expensive to do. So you might add a
last_order_dateto your userData.