多行SQL where语句

时间:2018-09-10 00:06:51

标签: sql

这可能是一个简单的SQL语句,但是现在我有一个“大脑冻结”。

我有这张桌子

variant_id | filter_id
1585593211       4
1585593211       48
1585593212       4
1585593212       49

我需要获取具有filters_id:4和48的variant_id。在这种情况下,我希望获得1585593211

3 个答案:

答案 0 :(得分:3)

您可以使用IN来获取filter_id 448的所有行。然后GROUP BY variant_id并检查filter_id子句中不同的HAVING的计数是否等于2。

SELECT variant_id
       FROM elbat
       WHERE filter_id IN (4, 48)
       GROUP BY variant_id
       HAVING count(DISTINCT filter_id) = 2;

答案 1 :(得分:2)

这是一个“套内查询”

您可以尝试根据条件获得count,然后找到variant_id个计数等于2

模式(MySQL v5.6)

CREATE TABLE T(
   variant_id INT,
   filter_id INT
);


INSERT INTO T VALUES (1585593211,4);
INSERT INTO T VALUES (1585593211,48);
INSERT INTO T VALUES (1585593212,4);
INSERT INTO T VALUES (1585593212,49);

查询#1

SELECT variant_id
FROM T t1
where filter_id in (4,48)
group by variant_id
HAVING COUNT(*) = 2;

| variant_id |
| ---------- |
| 1585593211 |

View on DB Fiddle

select variant_id
from T
group by variant_id
having sum(filter_id = 4) > 0 and 
       sum(filter_id = 48) > 0     

答案 2 :(得分:0)

SELECT variant_id
FROM TABLENAME where filter_id in (4,48) group by variant_id having count(distinct filter_id)>1;

group by,其中filter_id将过滤具有4和48的所有数据 特定的变体ID。 但是当我们添加
时,将满足实际要求  having count(distinct filter_id)>1;
这样可以确保filter_id中同时有 4和48