我有两个表:
Table A: Table B:
id name id a_id param
1 xxx 1 1 3
2 yyy 2 1 4
3 1 5
4 2 3
5 2 4
6 2 9
我需要从表A中选择这样的名称,其中来自B的3 <= param <= 5
的相关行数少于3。
在上述情况下,它应该仅产生yyy
,因为它只有2个来自B的相关行,
有3 <= param <= 5
。 xxx
有3条与此相关的行。
答案 0 :(得分:2)
您可以将GROUP BY
与HAVING
一起使用:
SELECT A.name
FROM A LEFT JOIN B ON A.id = B.a_id AND B.param BETWEEN 3 AND 5
GROUP BY A.name
HAVING COUNT(*) < 3
如果您需要表A
的所有列,则可以将INNER JOIN
与以上SELECT
一起使用:
SELECT A.*
FROM A INNER JOIN (
SELECT A.id
FROM A LEFT JOIN B ON A.id = B.a_id AND B.param BETWEEN 3 AND 5
GROUP BY A.id
HAVING COUNT(*) < 3
) A2 ON A.id = A2.id;
答案 1 :(得分:0)
嗯。 。 。您可以使用group by
和join
:
select a.*
from a left join
(select a_id, count(*) as cnt
from b
where param >= 3 and param <= 5
group by a_id
) b
on b.a_id = a.id
where b.cnt < 3 or b.cnt is null;