MySQL的选择的东西
问题描述:
我有两个表:MySQL的选择的东西
Article
-article_id
-name
-price
Attributes
-attribute_id
-article_id
-name
-value
我要选择一切从每一篇文章,如果名称为“色”的属性存在,我想选得过这个值。 这样一个例子结果如下:
Result_table
article_id; name; price; value
1; thing1; 24$;
2; thing2; 20$; red
3; thing3; 10$; blue
4; thing4; 19$;
答
你需要一个LEFT JOIN。条件name = 'color'
必须在ON子句中。这样您将保留没有“颜色”属性的文章。
SELECT art.*, attr.value
FROM Article art
LEFT JOIN Attributes attr
ON attr.article_id = art.article_id
AND attr.name = 'color'
+0
谢谢。完全做到了! – DerHelm
答
试试这个:
SELECT article_id, price, value FROM Article
LEFT JOIN Attributes
ON Article.article_id = Attributes.article_id
的LEFT JOIN
关键字左表(表1)返回的所有记录,以及来自右表的匹配记录(表2 )。如果不匹配,结果是右边的NULL
。
答
你可以做一个LEFT JOIN
与IF
,例如:
SELECT a.article_id, a.name a.price, IF(att.name = 'color', att.value, '') AS value
FROM article a
LEFT JOIN attributes att ON a.article_id = att.article_id;
见https://meta.*.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very -simple-sql-query – Strawberry