我尝试了一些子查询,但我没有成功。
假设我们有2个表:用户(iduser,名称),发票(idinvoice,title,status,iduser) 我们希望为每个用户显示总发票“已付款”,总发票“未付”(即状态字段)
我尝试过这样的查询
Select users.*, total_invoices_paid, total_invoices_unpaid
from users
LEFT JOIN (SELECT iduser, sum(if(status='paid',1,0)) AS total_invoices_paid, sum(if(status='unpaid',0,1)) AS total_invoices_unpaid
FROM invoices GROUP BY invoices.idinvoice) AS subinvoices
ON subinvoices.iduser=users.iduser
但我错了价值观,我觉得我错过了什么,但不知道是什么
有什么帮助吗?
由于
答案 0 :(得分:2)
我想你想要这个:
select u.*,
sum(i.status = 'paid') as total_invoices_paid,
sum(i.status = 'unpaid') as total_invoices_unpaid
from users u
left join invoices i on u.iduser = i.iduser
group by u.iduser;
在MySQL中,boolean分别被计算为1或0表示true或false。因此,在条件上使用sum
,我们可以找到计数。
使用子查询:
select u.*,
coalesce(i.total_invoices_paid, 0) as total_invoices_paid,
coalesce(i.total_invoices_unpaid, 0) as total_invoices_unpaid,
coalesce(i.total_invoices, 0) as total_invoices,
coalesce(i.total_paid_and_unpaid, 0) as total_paid_and_unpaid,
coalesce(i.total_with_non_null_status, 0) as total_with_non_null_status
from users u
left join (
select iduser,
sum(status = 'paid') as total_invoices_paid,
sum(status = 'unpaid') as total_invoices_unpaid,
count(1) as total_invoices,
sum(status in ('paid','unpaid')) as total_paid_and_unpaid,
count(status) as total_with_non_null_status
from invoices
group by iduser
) i on u.iduser = i.iduser
group by u.iduser;