简体   繁体   English

mySQL LEFT JOIN和COUNT表的出现次数

[英]mySQL LEFT JOIN and COUNT number of occurrences in right hand table

The following mySQL query returns a row structure that provides all rows from the Tickets Table and any matching information from the Sales Table. 以下mySQL查询返回一个行结构,该结构提供了票证表中的所有行以及销售表中的所有匹配信息。

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

However All we want to do is count the number of existing Rows from the right table for each ticket in order to track stock. 但是,我们要做的就是为每张票计算右表中现有行数,以跟踪库存。

I thought this would do it, but although it counts the number of tickets correctly it only returns one row from the ticket table and counts all sales in the column tcount. 我以为这样做是可以的,但是尽管它正确地计算了票数,但它只从票证表中返回一行,并统计了tcount列中的所有销售额。

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

You need a group by : 您需要一个group by

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

Either switch the table orders or do a RIGHT JOIN instead. 切换表顺序或执行RIGHT JOIN ie: 即:

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

or 要么

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM