我有以下查询
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
,在20
时返回c_id=5
有什么方法可以将两个查询组合起来形成这样的结果集?
c.cd c.c_id totals
moot 4 7
derp 5 20
答案 0 :(得分: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 :(得分: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;