简体   繁体   English

MySQL查询与另一个表的计数

[英]Mysql query with count on another table

I have two tables, one that has transaction information such as id, status, price and date. 我有两个表,其中一个包含交易信息,例如ID,状态,价格和日期。 I have another table that stores the number of items in that order as individual rows. 我还有另一个表,该表按该顺序将项目数存储为单独的行。 So, say transaction 2 has 10 items, there will be 10 rows in the second table of different items. 因此,假设交易2有10个项目,第二个表中的不同项目将有10行。 What im trying to do is run a query that lists transactions and the number of items sold in that transaction. 我想做的是运行一个查询,该查询列出了交易以及该交易中售出的商品数量。 I imagine this would require a count on the second table, but im not entirely sure of how to do it. 我想这需要在第二张桌子上数一数,但是我不确定如何做到这一点。 This is the basic layout of the database 这是数据库的基本布局

transaction id, date, price, discount, status
items: id, transaction_id, item_name, email, date_ordered, hash

Thanks in advance for all the help. 在此先感谢您提供的所有帮助。

Group by the columns in the transaction table you want to select. 按要选择的transaction表中的列分组。 Then add a count of the items 然后添加项目数

select t.id, count(i.id) as item_count
from transaction t
left join items i on i.transaction_id = t.id
group by t.id

You can do a left join on both tables like below 您可以在两个表上进行left join ,如下所示

select t.*, tab.total_order
from transaction t
left join
(
select transaction_id, count(*) as total_order
from items
group by transaction_id
) tab on t.id = tab.transaction_id

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

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