我想构建一个在执行时应该优化性能的查询。 下面是我的表结构:-
表名:- 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/