我有两张桌子,一张包含顾客,另一张包含预订 现在我想知道有多少预订来自一个人,但是用他们的名字而不是id来显示。
SELECT booking.id, COUNT(booking.id) AS idcount
FROM booking
GROUP BY booking.id ORDER BY idcount DESC;
输出是(正确计数):
id | idcount
----------+--------
2 | 8
1 | 4
我尝试显示名称而不是ID:
SELECT customer.lastn, customer.firstn, COUNT(booking.id) AS idcount
FROM booking, customer
GROUP BY customer.lastn, customer.firstn ORDER BY idcount DESC;
输出(错误计数):
lastn | firstn | idcount
----------+---------+--------
Adam | Michael | 13
Jackson | Leo | 13
13是预订总数(我只是关闭了输出)所以有来自的,但是我无法通过名称进行转换以获得正确的计数。
答案 0 :(得分:1)
您需要在FROM
子句中使用JOIN:
SELECT customer.lastn, customer.firstn, COUNT(booking.id) AS idcount
FROM booking
JOIN customer ON booking.id = customer.id
GROUP BY customer.lastn, customer.firstn
ORDER BY idcount DESC;
此处的JOIN说明了booking
表与customer
表的关系。