0

我有以下查询

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';

7何时返回和何时c_id=4返回20c_id=5

有什么方法可以将这两个查询结合起来形成这样的结果集?

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

2 回答 2

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 ;
于 2012-05-20T01:21:58.303 回答
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;
于 2012-05-20T01:22:26.803 回答