具有子查询的两个表的总和

时间:2014-01-27 10:26:46

标签: mysql sql select sum left-join

我有查询

SELECT c.user_id, 
   (SELECT COUNT(*) FROM jos_findme_bestof b WHERE b.user_id = c.user_id) as bCount,
   (SELECT COUNT(*) FROM jos_findme_pair   p WHERE p.user_id = c.user_id) as pCount,
   (SELECT COUNT(*) FROM jos_findme_style  s WHERE s.user_id = c.user_id) as sCount,

FROM   jos_findme c

如何创建一个列:bCount + pCount + sCount?

由于

4 个答案:

答案 0 :(得分:1)

如果要在查询中添加列:

   SELECT *,(bCount+pCount+sCount) as sumCount FROM(
    SELECT c.user_id, 
       (SELECT COUNT(*) FROM jos_findme_bestof b WHERE b.user_id = c.user_id) as bCount,
       (SELECT COUNT(*) FROM jos_findme_pair   p WHERE p.user_id = c.user_id) as pCount,
       (SELECT COUNT(*) FROM jos_findme_style  s WHERE s.user_id = c.user_id) as sCount,

    FROM   jos_findme c)

答案 1 :(得分:0)

试试这个

SELECT SUM(t.bCount+t.pCount+t.sCount) As TotalCount , t.user_id
FROM (
SELECT c.user_id as user_id, 
   (SELECT COUNT(*) FROM jos_findme_bestof b WHERE b.user_id = c.user_id) as bCount,
   (SELECT COUNT(*) FROM jos_findme_pair   p WHERE p.user_id = c.user_id) as pCount,
   (SELECT COUNT(*) FROM jos_findme_style  s WHERE s.user_id = c.user_id) as sCount
FROM jos_findme c ) t ;

答案 2 :(得分:0)

你可以试试这个

SELECT c.user_id, sum(b.count(*)+p.count(*)+s.count(*)) as totalcount 
    from jos_findme c 
    join  jos_findme_bestof b 
        on b.user_id = c.user_id 
    join jos_findme_pair p 
        on p.user_id = c.user_id 
    join jos_findme_style  s 
        on s.user_id = c.user_id

答案 3 :(得分:0)

试试这个:

SELECT c.user_id, 
      (IFNULL(b.bCount, 0) + IFNULL(p.pCount, 0) + IFNULL(s.sCount, 0)) AS totalCount
FROM jos_findme c
LEFT JOIN (SELECT b.user_id, COUNT(1) bCount 
           FROM jos_findme_bestof b 
           GROUP BY b.user_id 
         ) AS b ON b.user_id = c.user_id 
LEFT JOIN (SELECT p.user_id, COUNT(1) pCount 
           FROM jos_findme_pair p 
           GROUP BY p.user_id 
         ) AS p ON p.user_id = c.user_id 
LEFT JOIN (SELECT s.user_id, COUNT(1) sCount 
           FROM jos_findme_style s 
           GROUP BY s.user_id
         ) AS s ON s.user_id = c.user_id