8

在下面一对多

CREATE TABLE source(id int, name varchar(10), PRIMARY KEY(id));
CREATE TABLE params(id int, source int, value int);

其中 params.source 是 source.id 的外键

INSERT INTO source values(1, 'yes');
INSERT INTO source values(2, 'no');

INSERT INTO params VALUES(1,1,1);
INSERT INTO params VALUES(2,1,2);
INSERT INTO params VALUES(3,1,3);

INSERT INTO params VALUES(4,2,1);
INSERT INTO params VALUES(5,2,3);
INSERT INTO params VALUES(6,2,4);

如果我有一个参数值列表(比如 [1,2,3]),我如何在 SQL 中找到具有列表中所有值的所有源(源 1,“是”)?

谢谢

4

2 回答 2

11
SELECT s.*
FROM source AS s
 JOIN params AS p ON (p.source = s.id)
WHERE p.value IN (1,2,3)
GROUP BY s.id
HAVING COUNT(DISTINCT p.value) = 3;

您需要 DISTINCT 因为您的 params.value 不会被阻止重复。

于 2008-10-16T19:01:23.573 回答
7

编辑修改以处理给定源的值可能多次出现的情况。

试试这个:

SELECT
    *
FROM
    source
WHERE
    (
        SELECT COUNT(DISTINCT value)
        FROM params
        WHERE params.source = source.id
          AND params.value IN (1, 2, 3)
    ) = 3

您也可以将其重写为 GROUP BY:

SELECT
    source.*
FROM
    source
    INNER JOIN params ON params.source = source.id
WHERE
    params.value IN (1, 2, 3)
GROUP BY
    source.id,
    source.name
HAVING
    COUNT(DISTINCT params.value) = 3
于 2008-10-16T19:00:55.243 回答