2017-08-03 92 views
0

我有兩個表: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$; 
+1

見https://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very -simple-sql-query – Strawberry

回答

1

你需要一個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

0

試試這個:

SELECT article_id, price, value FROM Article 
LEFT JOIN Attributes 
ON Article.article_id = Attributes.article_id 

LEFT JOIN關鍵字左表(表1)返回的所有記錄,以及來自右表的匹配記錄(表2 )。如果不匹配,結果是右邊的NULL

0

你可以做一個LEFT JOINIF,例如:

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;