我有一个存储关系的mysql表.项目可以在一个方向上与另一个项目相关,或者两个项目可以彼此相关.
我想返回与我的主要项目相关的所有项目 - 但我还想检查相关项目是否与当前项目具有"反向关系"并将其显示为布尔值
|--------------|---------------|
| SKU | related_SKU |
|--------------|---------------|
| 0001 | 0099 |
| 0002 | 0099 |
| 0099 | 0001 |
|--------------|---------------|
Run Code Online (Sandbox Code Playgroud)
如果我想获得SKU = 0001的所有关系
SELECT related_SKU from relationships where SKU='0001'
Run Code Online (Sandbox Code Playgroud)
回报
|--------------|
| related_SKU |
|--------------|
| 0099 |
|--------------|
Run Code Online (Sandbox Code Playgroud)
但我想要的是
|--------------|---------------|
| related_SKU | reciprocal |
|--------------|---------------|
| 0099 | 1 |
|--------------|---------------|
Run Code Online (Sandbox Code Playgroud)
要么
SELECT related_SKU from relationships where SKU='0002'
|--------------|---------------|
| related_SKU | reciprocal |
|--------------|---------------|
| 0099 | 0 |
|--------------|---------------|
Run Code Online (Sandbox Code Playgroud)
最好的方法是什么?
您可能想尝试这样的事情:
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';
Run Code Online (Sandbox Code Playgroud)
测试用例:
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);
Run Code Online (Sandbox Code Playgroud)
互惠的结果:
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)
Run Code Online (Sandbox Code Playgroud)
结果没有倒数:
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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
952 次 |
| 最近记录: |