右侧表中的mySQL LEFT JOIN和COUNT个出现次数

时间:2015-12-03 12:53:14

标签: mysql count left-join

以下mySQL查询返回一个行结构,该结构提供Tickets Table中的所有行以及Sales表中的任何匹配信息。

SELECT tickets.*, sales.ID AS tcount 
FROM tickets LEFT JOIN sales ON tickets.ID = sales.ticket_ID

但是,我们要做的就是从每张票的右表中计算现有行的数量,以便跟踪库存。

我认为这会做到这一点,但是虽然它正确计算了故障单数量,但它只从故障单表中返回一行并计算列tcount中的所有销售额。

SELECT tickets.*, 
COUNT(sales.ID) AS tcount 
FROM tickets LEFT JOIN sales ON tickets.ID = sales.ticket_ID

2 个答案:

答案 0 :(得分:4)

您需要group by

SELECT tickets.*, COUNT(sales.ID) AS tcount 
FROM tickets LEFT JOIN
     sales
     ON tickets.ID = sales.ticket_ID
GROUP BY tickets.ID;

答案 1 :(得分:0)

切换表格订单或改为RIGHT JOIN。即:

SELECT tickets.*, 
COUNT(sales.ID) AS tcount 
FROM sales LEFT JOIN tickets ON tickets.ID = sales.ticket_ID

SELECT tickets.*, 
COUNT(sales.ID) AS tcount 
FROM tickets RIGHT JOIN sales ON tickets.ID = sales.ticket_ID