Mysql 从单独列中的值与3个不同值匹配的列中查找公共值

Mysql 从单独列中的值与3个不同值匹配的列中查找公共值,mysql,sql,Mysql,Sql,为这个措辞拙劣的标题道歉。我不完全确定如何描述这个问题。这对我来说也更容易 我有一个列出内容ID和值的数据库表。一个ID可以有不同的值,因此ID=1可能有1行或多行,具体取决于与它关联的值的数量 在本例中,我想查找与3个不同值关联的所有ID。目前,SQL是在几个子查询中编写的,但是如果要搜索很多不同的值,则需要花费大量时间来解析 例如: Select id from table1 where type = 'report' and id in (select id from table2 whe

为这个措辞拙劣的标题道歉。我不完全确定如何描述这个问题。这对我来说也更容易

我有一个列出内容ID和值的数据库表。一个ID可以有不同的值,因此ID=1可能有1行或多行,具体取决于与它关联的值的数量

在本例中,我想查找与3个不同值关联的所有ID。目前,SQL是在几个子查询中编写的,但是如果要搜索很多不同的值,则需要花费大量时间来解析

例如:

Select id from table1 where type = 'report'
and id in (select id from table2 where value=1)
and id in (select id from table2 where value=2)
and id in (select id from table2 where value=3) 
order by id

内容可以有许多链接表来执行子查询搜索。添加越多,运行时间就越多,这并不理想。减少子查询数量的最佳方法是什么?

您正在寻找“HAVING”关键字。在没有看到数据示例的情况下,我可能无法正确地实现它,但这应该为您提供一个研究方向

SELECT id 
FROM table1
WHERE type = 'report'
GROUP BY id
HAVING COUNT(id) = 3

您可以使用不同的表名别名对表2使用内部联接

Select t1.id 
from table1  t1
where t1.type = 'report'
INNER JOIN table2 t2a ON t1.id = t2a.id  and t2a.value  = 1
INNER JOIN table2 t2b ON t1.id = t2b.id  and t2b.value  = 2
INNER JOIN table2 t2c ON t1.id = t2c.id  and t2c.value  = 3 
order by t1.id

为了获得更好的性能,您应该在表2的列(value,id)上添加一个复合索引,在表1的列(type,id)上添加一个复合索引

select t1.id
from table1 t1
where t1.type = 'report' and
      exists (select 1 
              from table2 t2
              where t2.id = t.id and t2.value = 1
             ) and
      exists (select 1 
              from table2 t2
              where t2.id = t.id and t2.value = 2
             ) and
      exists (select 1 
              from table2 t2
              where t2.id = t.id and t2.value = 3
             ) ;
order by t1.id

table1(type,id)
table2(id,value)
上有索引,我希望这会有最好的性能。

显示一些数据示例和预期结果这大大加快了速度。谢谢。为了获得更好的性能,您应该在表2的列(值,id)和表1的列类型,id)上添加一个复合索引。。答案更新。我也喜欢这个答案的优雅。谢谢@弗洛伊德。我希望它有最好的表现。