mysql select 如果存在的话

mysql select something if exists

我有两个表:

Article
-article_id
-name
-price

Attributes
-attribute_id
-article_id
-name
-value

我想 select 每篇文章的所有内容,如果存在名称为 "color" 的属性,我也想 select 编辑此值。 因此示例结果如下所示:

Result_table
article_id;  name;    price;  value
         1;  thing1;    24$;
         2;  thing2;    20$;  red
         3;  thing3;    10$;  blue
         4;  thing4;    19$;

试试这个:

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

LEFT JOIN关键字returns左边table的所有记录(table1),以及右边table(table2).如果没有匹配,结果是从右边开始NULL

您可以用 IF 做一个 LEFT JOIN,例如:

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;

您需要一个 LEFT JOIN。条件 name = 'color' 必须在 ON 子句中。这样您将保留没有 'color' 属性的文章。

SELECT art.*, attr.value
FROM Article art
LEFT JOIN Attributes attr
  ON  attr.article_id = art.article_id
  AND attr.name = 'color'