1

我在这里有一个相对简单的查询,它没有返回预期的行数。我认为以下查询对于我的情况应该可以正常工作,但是我必须在这里遗漏一些重要的东西,以确保不是所有行都显示多次。!

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

4 回答 4

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 连接

于 2013-05-23T12:08:39.773 回答
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
于 2013-05-23T12:09:35.643 回答
1

似乎您先命名 table 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,它允许匹配 NULL 值。也许您需要做的就是更改为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 = 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'
于 2013-05-23T11:53:12.447 回答
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'
于 2013-05-23T11:58:46.550 回答