mysql - 使用 MySQL 查询查找具有匹配行的 ID

标签 mysql sql

+----------+---------+---------+-----------+-----------+--------------+
| entry_id | item_id | stat_id | stat_type | int_value | string_value |
+----------+---------+---------+-----------+-----------+--------------+
|        1 | 4255    |      10 | int       |        54 | NULL         |
|        2 | 4255    |      16 | int       |       443 | NULL         |
|        3 | 4255    |      56 | int       |        13 | NULL         |
|        4 | 6544    |      10 | int       |        54 | NULL         |
|        5 | 6544    |      56 | int       |        13 | NULL         |
|        6 | 6544    |      16 | int       |       443 | NULL         |
|        7 | 8570    |      56 | int       |        13 | NULL         |
|        8 | 8570    |      10 | int       |        76 | NULL         |
|        9 | 8570    |      72 | int       |         1 | NULL         |
+----------+---------+---------+-----------+-----------+--------------+

以上是我的表格示例。 任务是为表提供目标“item_id”值,取回与目标具有相同行的“item_id”。

在上面的示例中,提供 4255 的“item_id”将返回 6544,因为这两个“item_id”值都在三行中找到,每一行在其他方面彼此匹配(“entry_id”除外)。

本质上,我需要找出数据库中是否有另一个“item_id”,它在所有方面都与目标相同。如果它具有相同的行但也在其他行中找到,则不会将其归类为匹配项。

是否可以将此类操作作为 SQL 查询的一部分? 我目前正在用 C# 代码执行此操作,我在其中逐行检查包含目标“item_id”的每一行,以寻找匹配项。这看起来效率很低。

最佳答案

假设你没有重复项(组合 (item_id, stat_id, stat_type, int_value, string_value) 是唯一的)并且只有 string_value 可以为 NULL,那么你可以加入完全匹配并比较行数(数学的数量必须等于两个项目的行数)。

select t2.item_id
from t t1
join t t2 using(stat_id, stat_type, int_value)
where t1.item_id = 4255
  and t2.item_id <> t1.item_id
  and t2.string_value <=> t1.string_value
group by t1.item_id, t2.item_id
having count(*) = (select count(*) from t where t.item_id = 4255)
   and count(*) = (select count(*) from t where t.item_id = t2.item_id)

演示:http://rextester.com/RIU87596

关于mysql - 使用 MySQL 查询查找具有匹配行的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43416791/

相关文章:

MySQL 按列值分组 block ,按其他列排序

mysql - 另一个 MySQL 语法错误

sql - 使用数据库/sql时如何获取返回的行数?

sql - 在不使用 DBCC 的情况下确定每个 SQL 表的页数

MySQL 三个表的连接

mysql - 提高大型 SQL 查询的效率

php - 如何在通过 fopen 创建的 php 文件中包含变量

php - 在php mysql中获取 child 及其 parent 关系的所有详细信息

mysql - SQL 仅选择列上具有最大值的行

php - mssql_connect 神秘地停止工作