简体   繁体   中英

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.

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.

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

You need a 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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