LEFT JOIN ALL results
Hello guys I have a problem with a query and left join
I have 2 tables products and characteristics I know some required characteristics with id 1,3,6
SELECT * FROM products
LEFT JOIN characteristics ...
WHERE characte开发者_运维技巧ristics_id IN (1,2,6)
But this not works for me because I need the products with ALL of this characteristics, not only one.
Really I need
SELECT * FROM products
INNER JOIN characteristics as c1 ... AND c1.id=1
INNER JOIN characteristics as c2 ... AND c2.id=2
INNER JOIN characteristics as c2 ... AND c2.id=3
...
But it don't like me, there must be a simpler and efficient
Thank you.
First of all, you don't need a LEFT JOIN
at all.
Second, your first attempt seems perfectly valid and I think it's the most efficient (when there are indexes on the tables to be joined). But I'm adding another way (that seems more simple as it has only 1 join).
Simple (to add more than 3 characteristics):
SELECT p.*
FROM products AS p
INNER JOIN characteristics AS c ON ...
WHERE c.id IN (1, 3, 6)
GROUP BY p.id
HAVING
COUNT(*) = 3 --- or COUNT(DISTINCT c.id)
--- depending on your data
More efficient (in most cases, in other words: test, test and test again in your tables with various sizes and number of ids):
SELECT p.*
FROM products AS p
INNER JOIN characteristics AS c1 ON ...
INNER JOIN characteristics AS c2 ON ...
INNER JOIN characteristics AS c3 ON ...
WHERE c1.id = 1
AND c2.id = 3
AND c3.id = 6
maybe you could use a subselect and so something like this:
SELECT * FROM
products
WHERE
(
SELECT COUNT(*) FROM
characteristics
WHERE product = products.id AND characteristics_id IN (1,2,3)
) >= 3;
note that this isn't tested because you havn't posted your exact table-definitions.
精彩评论