MySQL与特定的WHERE子句连接

时间:2016-01-03 17:15:20

标签: php mysql

我有一个简单的数据库

enter image description here

通过此查询,我获得了所有用户和他们购买的产品数量:

SELECT
  c.id,
  cd.name,
  cd.surname,
  COUNT(p.name) as bought
FROM shopping s
 JOIN client c ON s.client_id = c.id
 JOIN client_details cd ON c.id = cd.client_id
 JOIN product p ON s.product_id = p.id
GROUP BY c.id;

它非常好,但我必须选择所有用户和购买的特定产品的数量。有了这个查询,我只有在用户购买了至少一种产品时才能得到它:

SELECT
  c.id,
  cd.name,
  cd.surname,
  COUNT(p.name) as bought
FROM shopping s
 JOIN client c ON s.client_id = c.id
 JOIN client_details cd ON c.id = cd.client_id
 JOIN product p ON s.product_id = p.id
WHERE p.name = 'sugar'
GROUP BY c.id;

我希望获得所有用户的列表,如果特定用户没有'购买特定产品,输出应该是0。

1 个答案:

答案 0 :(得分:0)

使用条件聚合:

SELECT c.id, cd.name, cd.surname,
       MAX(p.name = 'sugar') as SugarFlag
FROM shopping s JOIN
     client c
     ON s.client_id = c.id JOIN
     client_details cd
     ON c.id = cd.client_id JOIN
     product p
     ON s.product_id = p.id
GROUP BY c.id;