LEFT JOIN ALL结果

时间:2011-06-21 11:37:43

标签: mysql join

大家好,我的查询有问题并且离开了

我有2个表产品和特性 我知道id 1,3,6

的一些必需特征
 SELECT * FROM products
    LEFT JOIN characteristics ...
    WHERE characteristics_id IN (1,2,6)

但这不适合我,因为我需要具有所有这些特性的产品,而不仅仅是一个。

我真的需要

 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
...

但它不喜欢我,必须有一个更简单有效的

谢谢。

2 个答案:

答案 0 :(得分:0)

也许你可以使用一个subselect,所以像这样:

SELECT * FROM
  products
WHERE
  (
  SELECT COUNT(*) FROM
    characteristics
  WHERE product = products.id AND characteristics_id IN (1,2,3)
  ) >= 3;

请注意,这未经过测试,因为您没有发布确切的表格定义。

答案 1 :(得分:0)

首先,您根本不需要LEFT JOIN

其次,您的第一次尝试似乎完全有效,我认为它是最有效的(当要加入的表上有索引时)。但我正在添加另一种方式(这似乎更简单,因为它只有1个连接)。


简单(添加3个以上的特征):

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

更多高效(在大多数情况下,换句话说:在具有各种尺寸和ID数量的表格中再次进行测试,测试和测试):

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