SQL选择取决于条件计数

时间:2019-01-23 22:10:24

标签: sql select count inner-join

我有两个表:

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 <= 5xxx有3条与此相关的行。

2 个答案:

答案 0 :(得分:2)

您可以将GROUP BYHAVING一起使用:

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;
  

演示: https://www.db-fiddle.com/f/jBCw5G1LvrRC37TLVx3UsB/1

答案 1 :(得分:0)

嗯。 。 。您可以使用group byjoin

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;