如何从嵌套选择中获取嵌套的两个值? MySQL的

时间:2014-11-14 12:48:34

标签: mysql sql

查询:

 SELECT business.bussId,
 (select count(invoices.userId) from invoice where invoice.userId = '3000' ) 
 as invoiceCount,    
 (select SUM(invoices.price) from invoice where invoice.userId = '3000' )
 as invoiceprice ,
 FROM business WHERE business.bussId=100

如何使用一个嵌套选择来获取发票价格和invoiceCount?

1 个答案:

答案 0 :(得分:2)

将子查询移动到from子句:

SELECT b.bussId, i.invoiceCount, i.invoiceprice
FROM business b cross join
     (select count(i.userId) as invoiceCount, SUM(i.price) as invoiceprice
      from invoice i
      where i.userId = '3000'
     ) i
WHERE b.bussId = 100;

实际上你可以在没有子查询的情况下编写它,但你的问题是关于使用子查询。

该表格将是:

SELECT b.bussId, count(i.userId) as invoiceCount, SUM(i.price) as invoiceprice
FROM business b left join
     invoice i
     on i.userId = '3000' and b.bussId = 100
GROUP BY b.bussId;