加入,选择'字符串'如果没有找到

时间:2014-03-16 11:42:41

标签: mysql sql

SELECT p.name, p.price, COALESCE(s.size, 'Medium')
FROM product p
LEFT JOIN sizes s ON p.id = s.product
WHERE p.id = 1

如果sizes表中没有提及产品,它是否选择该产品?

  id      name      price
  1.     cap         50
  2.     glove       75


 id      product                   size
  1.     2                       'small'
  2.     2                       'large'  

2 个答案:

答案 0 :(得分:0)

怎么样:

     SELECT p.name, p.price, IF( EXISTS(
         SELECT size
         FROM sizes s LEFT JOIN product p ON p.id = s.product
         WHERE p.id = 1
          ), s.size, 'Medium') as siz
    FROM product p
    LEFT JOIN sizes s ON p.id = s.product
    WHERE p.id = 1 

答案 1 :(得分:-1)

WHERE条件

外,您的查询没问题
SELECT p.name, p.price, COALESCE(s.size, 'Medium')
FROM product p
LEFT JOIN sizes s ON p.id = s.product

以下是SQL Fiddle的代码 如果想通过查询实现其他目的,请告诉我。