Let’s say I have a table that lists various toys and the types of batteries they take:
toy_id battery_id battery_qty
1 3 1
2 2 4
2 3 1
3 1 1
I want to construct a query that will tell me which toys take both battery types 2 and 3 (but might take others as well). In the example above, that’s toy_id 2.
How do I go about writing a query like that?
Here’s what I have so far, but it seems messy:
SELECT t1.toy_id,
t1.battery_id b1, t2.battery_id b2,
t1.battery_qty qty1, t2.battery_qty qty2
FROM toys t1
LEFT JOIN toys t2
ON t1.toy_id = t2.toy_id
WHERE t1.battery_id = 2
AND t2.battery_id = 3
HAVING q1 > 0
AND q2 > 0
ORDER BY toy_id ASC;
The results look correct, but I’m curious if I missed something.
I think join is not really need here. You only need to count the number of instances of the record and which is equal to the number of conditions you have searched.
but if unique constraint was not define on battery_id for each toy_id,
DISTINCTis need on theHAVINGclause.