mysql - 寻找优化的 MySQL 查询

标签 mysql

我想构建一个在执行时应该优化性能的查询。 下面是我的表结构:-

表名:- list

表结构:-

item_id int(50) Primary key,
item_name varchar(50),
matchingItemID int(50).

从上表中,我想找到匹配的项目对, 即,如果 A 和 B 分别是 item_id 为 1 和 2 的两个项目,则名为 matchingItemID 的字段中的值必须分别为 2 和 1。

matchingItemID 是添加的项目的 item_id。

例如

item_id     item_name      matchingItemID
   1            A                2
   2            B                1

因此,构建的查询应返回如下输出:-

A - B

我已经尝试过一个查询,但它在执行时需要时间,因此我认为它没有优化性能。

下面是我构建的查询:-

SELECT a.item_id, b.item_id
FROM inventory a, inventory b
WHERE a.matchingItemID = b.item_id
AND b.matchingItemID = a.item_id
AND a.item_id != b.item_id;

最佳答案

如果项目总是相互匹配,你可以这样做:

SELECT a.item_id, b.item_id
FROM inventory a
JOIN inventory b ON a.matchingItemID = b.item_id

此外,您可以将索引添加到 matchingItemID 列。

编辑

看似多余,但这是您要求的:

SELECT a.item_id, b.item_id
FROM inventory a
JOIN inventory b ON a.matchingItemID = b.item_id AND b.matchingItemID = a.item_id

关于mysql - 寻找优化的 MySQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14080030/

相关文章:

sql - MySQL 递归查询

c# - 针对 Excel 列循环遍历 SQL 数据库列的最快方法 - C#

php - 我想使用 PhP 删除组合框中的选定项目,并且该项目也必须反射(reflect)在数据库中

javascript - 如何从 cytoscape.js 中的 mysql 数据库中检索节点和元素?

PHP PDO 不会更新数据库

mysql - 从列中选择最大值并从另一列中选择相应的值

MySQL 按两列排序,一个 ASC 和一个 RAND()

mysql - 更改字段上的部分字符串

mysql - 从另一个表插入表,但如果已存在则更新

sql - 合并 3NF mysql 表中多行的内容