检查mysql中的互惠关系。一个简单的一个表问题

时间:2010-06-02 09:45:59

标签: sql mysql

我有一个存储关系的mysql表。项目可以在一个方向上与另一个项目相关,或者两个项目可以相互关联。

我想返回与我的主要项目相关的所有项目 - 但我还想检查相关项目是否与当前项目具有“反向关系”并将其显示为布尔值

 |--------------|---------------|
 |    SKU       |  related_SKU  |
 |--------------|---------------|
 | 0001         |  0099         |
 | 0002         |  0099         |
 | 0099         |  0001         |
 |--------------|---------------|

如果我想获得SKU = 0001

的所有关系
SELECT related_SKU from relationships where SKU='0001'

返回

 |--------------|
 | related_SKU  |
 |--------------|
 | 0099         |
 |--------------|

但我想要的是

 |--------------|---------------|
 | related_SKU  |   reciprocal  |
 |--------------|---------------|
 | 0099         |      1        |
 |--------------|---------------|

 SELECT related_SKU from relationships where SKU='0002'

 |--------------|---------------|
 | related_SKU  |   reciprocal  |
 |--------------|---------------|
 | 0099         |      0        |
 |--------------|---------------|

最好的方法是什么?

2 个答案:

答案 0 :(得分:5)

你可能想尝试这样的事情:

SELECT r1.related_SKU,
       IF(( SELECT COUNT(*) 
            FROM   relationships r2 
            WHERE  r2.SKU = r1.related_SKU AND r2.related_SKU = r1.SKU
       ) > 0, 1, 0) AS reciprocal
FROM   relationships r1
WHERE  r1.SKU = '0001';

测试用例:

CREATE TABLE relationships (SKU int, related_SKU int);

INSERT INTO relationships VALUES (1, 99);
INSERT INTO relationships VALUES (2, 99);
INSERT INTO relationships VALUES (99, 1);

倒数的结果:

SELECT r1.related_SKU,
       IF(( SELECT COUNT(*) 
            FROM   relationships r2 
            WHERE  r2.SKU = r1.related_SKU AND r2.related_SKU = r1.SKU
       ) > 0, 1, 0) AS reciprocal
FROM   relationships r1
WHERE  r1.SKU = '0001';

+-------------+------------+
| related_SKU | reciprocal |
+-------------+------------+
|          99 |          1 |
+-------------+------------+
1 row in set (0.00 sec)

没有互惠的结果:

SELECT r1.related_SKU,
       IF(( SELECT COUNT(*) 
            FROM   relationships r2 
            WHERE  r2.SKU = r1.related_SKU AND r2.related_SKU = r1.SKU
       ) > 0, 1, 0) AS reciprocal
FROM   relationships r1
WHERE  r1.SKU = '0002';

+-------------+------------+
| related_SKU | reciprocal |
+-------------+------------+
|          99 |          0 |
+-------------+------------+
1 row in set (0.00 sec)

答案 1 :(得分:3)

select r.related_sku, recip.sku is not null as reciprocal
from relationships r
  left join relationships recip on (r.related_sku = recip.sku && recip.related_sku = r.sku)
where r.sku = '0001'