好吧,我有一个来自客户端的数据库,其中表没有很好的关系,是一团糟。获取我需要的信息的问题是我需要关联表的字段与我将要使用的表无关。
我会说清楚:
共有3个表格:访问量,咖啡和付款。
桌上的咖啡有payment_id。 表访问有coffee_id。 表付款没有ID !!
我想知道每次咖啡有多少次访问以及为每种咖啡付了多少钱。
结果应该是这样的:
访问|咖啡|付款
8234 | MOCHA | 829
那么,我怎么知道所有的付款,咖啡是什么以及它有多少次访问?
可能很明显,但我对同样的事情感到不知所措。
感谢大家的帮助!
答案 0 :(得分:0)
获取每种咖啡的访问量:
SELECT c.name AS coffee, IFNULL(count(v.coffee_id), 0) AS visits
FROM coffees AS c
LEFT JOIN visits AS v ON c.id = v.coffee_id
GROUP BY c.id
为每种咖啡付款:
SELECT c.name AS coffee, IFNULL(count(p.id), 0) AS payments
FROM coffees AS c
LEFT JOIN payments AS p ON c.payment_id = p.id
GROUP BY c.id
要在一个查询中同时获取它们:
SELECT coffee, MAX(visits) AS visits, MAX(payments) AS payments
FROM (
SELECT c.name AS coffee, IFNULL(count(v.coffee_id), 0) AS visits, 0 AS payments
FROM coffees AS c
LEFT JOIN visits AS v ON c.id = v.coffee_id
GROUP BY c.id
UNION
SELECT c.name AS coffee, 0 as visits, IFNULL(count(p.id), 0) AS payments
FROM coffees AS c
LEFT JOIN payments AS p ON c.payment_id = p.id
GROUP BY c.id) x
GROUP BY coffee