I have the following SQL:
SELECT `table1`.`value`, `table2`.*
FROM `table2`
INNER JOIN `table1` ON `table2`.`product_id` = `table1`.`entity_id`
WHERE `table2`.`created_at` > '2012-04-23' and
(`table1`.`value` = 264 OR `table1`.`value` = 260)
order by order_id
Which returns a result set like this (This is only a part of the returned results):
value order_id ...
260 1234
260 1235
260 1236
264 1236
260 1237
260 1238
260 1239
264 1239
264 1240
260 1241
What I want is a query that will take these results and only return orders where the order_id contains both value 260 and 264. Based on this example, the end result I am looking for is
260 1236
264 1236
260 1239
264 1239
My thought is this can be done with a subset but I am not exactly sure on the details to accomplish it.
How about this?
(sorry for omitting apostrophes, I am not aware what are mysql requirements in this field; this syntax is ms-sql compliant)
This can be accomplished with relational division:
result:
where your query is
your_table_or_query
andis
divisor
.This will return the order ids 1236 and 1239; they can then be
join
ed to original query to get all the rows with those order ids if that's what you want.Full query along with insert statements:
Result:
this will return a list of orders that have both values 260 and 264 - if someone needs just this result instead of duplicated results for each of the value:
or if someone wanted faster solution without costly
having
clauses (+ of course you can store the query or use a CTE instead of just repeating it)Left join so it only matches the table1.value results with matches and leave the info from the other table out