LEFT JOINS在MySQL中创建了很多行

时间:2013-05-23 11:48:49

标签: mysql sql

我在这里有一个相对简单的查询,它没有返回预期的行数。我认为以下查询应该适用于我的情况,但我必须缺少必要的东西,以确保不会多次显示所有行。!

SELECT p.*, c.value AS color, g.value AS gender, p.value AS price
FROM   products p
LEFT JOIN product_fields c ON c.product_id = p.id AND c.name = 'color'
LEFT JOIN product_fields g ON g.product_id = p.id AND g.name = 'gender'
LEFT JOIN product_fields pp ON pp.product_id = p.id AND pp.name = 'price'

4 个答案:

答案 0 :(得分:2)

LEFT JOIN包括第一个表中的所有记录和第二个表中的所有匹配记录,假设查询不排除第二个表中的空值。

但INNER JOIN从结果集中排除了两个表中都不存在的任何记录。

所以这可能会对你有所帮助:

SELECT p.*, c.value AS color, g.value AS gender, p.value AS price
FROM   products p
INNER JOIN product_fields c ON c.product_id = products.id
INNER JOIN product_fields g ON g.product_id = products.id
INNER JOIN product_fields pp ON pp.product_id = products.id
WHERE c.name = 'color' AND g.name = 'gender' AND pp.name = 'price'

有关加入类型MySQL Joins

之间的差异

答案 1 :(得分:2)

LEFT JOIN将获得与name = ..条件不匹配的不匹配行,这就是为什么你会获得更多行,我建议改为使用INNER JOIN,或者如果你需要使用LEFT JOIN你可以这样做:

SELECT p.*, c.value AS color, g.value AS gender, p.value AS price
FROM   products p
LEFT JOIN
(
   SELECT *
   FROM product_fields
   WHERE name = 'color'
) AS c ON c.product_id = products.id 
LEFT JOIN 
(
   SELECT * 
   FROM product_fields
   WHERE name = 'gender'
) AS g ON g.product_id = products.id 
LEFT JOIN 
(
   SELECT * 
   FROM product_fields
   WHERE name = 'price'
) AS pp ON pp.product_id = products.id

答案 2 :(得分:1)

您似乎将表products AS p命名为product_fields AS p,然后又命名为SELECT p.*, c.value AS color, g.value AS gender, p.value AS price FROM products p LEFT JOIN product_fields c ON c.product_id = p.id AND c.name = 'color' LEFT JOIN product_fields g ON g.product_id = p.id AND g.name = 'gender' LEFT JOIN product_fields pr ON pr.product_id = p.id AND pr.name = 'price' 。试试这个:

LEFT JOIN

注意,您使用INNER JOIN,它允许匹配NULL值。也许你需要做的就是改为SELECT p.*, c.value AS color, g.value AS gender, p.value AS price FROM products p INNER JOIN product_fields c ON c.product_id = p.id AND c.name = 'color' INNER JOIN product_fields g ON g.product_id = p.id AND g.name = 'gender' INNER JOIN product_fields pr ON pp.product_id = p.id AND pp.name = 'price'

{{1}}

答案 3 :(得分:0)

您为表p添加了别名products,但在使用表名的联接中,尝试使用联接上的别名来查看它是否可以解决您的问题:

SELECT p.*, c.value AS color, g.value AS gender, p.value AS price
FROM   products p
LEFT JOIN product_fields c ON c.product_id = p.id AND c.name = 'color'
LEFT JOIN product_fields g ON g.product_id = p.id AND g.name = 'gender'
LEFT JOIN product_fields pp ON pp.product_id = p.id AND pp.name = 'price'