是否有任何查询可以找到此 ID 信息?

Is there any query to find this id information?

她是我的样本 table:

+--------+-------+-----+
|  name  | value | id  |
+--------+-------+-----+
| value1 |     1 | 100 |
| value2 |     2 | 100 |
| value1 |     1 | 200 |
| value2 |     3 | 200 |
| value1 |     1 | 300 |
| value2 |     4 | 300 |
|        |       |     |
+--------+-------+-----+

如何设置 SQL 查询以检索给定 value1 = 1value2 = 2id 值 100?

如果我理解正确,使用 having 子句的聚合可以满足您的要求:

select id
from t
group by id
having count(*) filter (where name = 'value1' and value = 1) = 1 and
       count(*) filter (where name = 'value2' and value = 2) = 1 ;

   

SELECT id from TABLE_NAME WHERE value IN (1, 2);

value 列为 1 或 2[=10 时,这将从 table 中检索 id 列=]

按id分组并在having子句中设置条件:

select id
from tablename
where (name, value) in (('value1', 1), ('value2', 2))
group by id
having count(distinct value) = 2 

参见demo

一例。参见:

  • How to filter SQL results in a has-many-through relation

此查询通常 比目前建议的查询更有效

SELECT id
FROM  (SELECT id FROM tbl WHERE name = 'value1' AND value = 1) t1
JOIN  (SELECT id FROM tbl WHERE name = 'value2' AND value = 2) t2 USING (id);

或等价物(产生相同的查询计划):

SELECT id
FROM   tbl t1
JOIN   tbl t2 USING (id)
WHERE  t1.name = 'value1' AND t1.value = 1
AND    t2.name = 'value2' AND t2.value = 2;

db<>fiddle here

不在查询中强制执行唯一性(像其他答案一样),因为我假设 table 中的一个或多个约束已经这样做了。

(name, value, id) 上有一个“覆盖”索引。根据您未公开的 table 定义,优化索引变化是可能的。

但如果您有能力改变它,请首先重新考虑您的关系设计。 EAV 模型通常是次优的。参见: