与建议的表格一样,我希望输出所有产品的清单,但同时列出谁购买了每个产品。
我的数据结构如下
products
=================
|prodId |prod |
=================
|1 |hat |
|2 |shirt |
|3 |watch |
|4 |cream |
|5 |pizza |
=================
orders
=========================
|ordID |prodID |cust |
=========================
|1 |2 |paul |
|2 |4 |paul |
|3 |4 |bob |
|4 |5 |jane |
|5 |4 |sarah |
=========================
我希望收到这个结果,如果没有客户购买,那将是null
=================
|prod |cust |
=================
|hat |null |
|shirt |paul |
|watch |null |
|cream |paul |
|cream |bob |
|cream |sarah |
|pizza |jane |
=================
答案 0 :(得分:0)
SELECT p.prod, o.cust, count(o.*) count_of
FROM products as p
LEFT OUTER JOIN orders as o ON p.prodid = o.prodid
GROUP BY prod, cust
要获得以from products
开头的al产品列表,请使用OUTER
联接,该联接允许返回不匹配的行以及匹配的行。
然后group by
将列表缩减为唯一组合,并启用聚合这样的计数。
答案 1 :(得分:0)
以下查询应该完成工作
select p.prod, o.cust from products p left outer join orders o on p.prodId = o.prodId;