我有三个表:我们称其为CUSTOMER,LOG和REVIEW
客户表为:
id name == ==== 1 John 2 Jane 3 Mike
LOG表是
id customer_id created_at == =========== ========== 1 1 2015-06-10 2 1 2015-06-10 3 2 2015-06-11 4 1 2015-06-13 5 2 2015-06-15 6 1 2015-06-15
REVIEW表是
id customer_id created_at == =========== ========== 1 1 2015-06-10 2 2 2015-06-10 3 2 2015-06-11 4 1 2015-06-13 5 1 2015-06-15 6 1 2015-06-15 7 1 2015-06-18
我想要什么
CUSTOMER_ID NAME LOG_QTY REVIEW_QTY =========== ==== ======= ========== 1 John 4 5 2 Jane 2 2 3 Mike 0 0
我得到了:
CUSTOMER_ID NAME LOG_QTY REVIEW_QTY =========== ==== ======= ========== 1 John 20 20 2 Jane 4 4 3 Mike 0 0
我的查询:
select CUSTOMER.ID, CUSTOMER.NAME, count(REVIEW.CUSTOMER_ID) as REVIEW_QTY, count(LOG.CUSTOMER_ID) as LOG_QTY from CUSTOMER left join REVIEW on REVIEW.CUSTOMER_ID = CUSTOMER.ID left join LOG on LOG.CUSTOMER_ID = CUSTOMER.ID group by CUSTOMER.ID order by CUSTOMER.ID
如果您在不使用COUNT()和GROUP BY的情况下运行查询,则会看到发生了什么:
COUNT()
GROUP BY
select CUSTOMER.ID, CUSTOMER.NAME, REVIEW.CUSTOMER_ID as REVIEW_QTY, LOG.CUSTOMER_ID as LOG_QTY from CUSTOMER left join REVIEW on REVIEW.CUSTOMER_ID = CUSTOMER.ID left join LOG on LOG.CUSTOMER_ID = CUSTOMER.ID order by CUSTOMER.ID
这将为每个可能的行组合返回一行,并CUSTOMER_ID从三个表中返回相同的行(就是INNER JOIN这样)。然后COUNT就算是他们!
CUSTOMER_ID
INNER JOIN
COUNT
这应该给您您需要的:
select CUSTOMER.ID, CUSTOMER.NAME, (select count(*) from REVIEW where CUSTOMER_ID = CUSTOMER.ID) as REVIEW_QTY, (select count(*) from LOG where CUSTOMER_ID = CUSTOMER.ID) as LOG_QTY from CUSTOMER order by CUSTOMER.ID