2012-05-20 77 views
0

我有以下查詢如何結合SELECT查詢和COUNT(*)查詢?

SELECT 
      c.cd, 
      c.c_id 
FROM 
      f f 
      INNER JOIN s s 
        ON s.s_id = f.s_id 
      INNER JOIN c c 
        ON c.c_id = s.c_id 
WHERE f.m_id = 2 
      AND f.deleted = 'no' 
GROUP BY s.c_id 
ORDER BY f.update_datetime DESC ; 

它返回一個示例結果集:

c.cd c.c_id 
moot 4 
derp 5 

我有基於上述結果集的c.c_id另一個查詢其迭代對於在上述結果中的每個記錄設置:

SELECT COUNT(*) as totals FROM s 
WHERE c_id =? 
AND status='good'; 

回報7c_id=4和返回20c_id=5

有什麼辦法可以結合這兩個查詢來形成這樣的結果集?

c.cd c.c_id totals 
moot 4  7 
derp 5  20 

回答

2

試試這個:

SELECT 
      c.cd, 
      c.c_id, 
      (SELECT COUNT(*) FROM s WHERE c_id = c.c_id AND STATUS = 'good') totals 
FROM 
      f INNER JOIN s ON s.s_id = f.s_id 
      INNER JOIN c c ON c.c_id = s.c_id 
WHERE  f.m_id = 2 AND f.deleted = 'no' 
GROUP BY s.c_id 
ORDER BY f.update_datetime DESC ; 
1

像這樣的事情?

SELECT c.cd, c.c_id 
     ,SUM(CASE WHEN s.status = 'good' THEN 1 ELSE 0 END) AS totals 
    FROM f f 
    INNER JOIN s s ON s.s_id = f.s_id 
    INNER JOIN c c ON c.c_id = s.c_id 

WHERE f.m_id =2 
    AND f.deleted='no' 

GROUP BY s.c_id 
ORDER BY f.update_datetime DESC;