我有一个(遗留)表,其中包含列:
bug_num build_id closed_to
1 3 NULL
2 4 NULL
3 NULL 1
4 3 NULL
5 NULL 2
我想编写一个查询,它将从特定版本中选择所有错误,以及所有对该版本中的错误关闭的错误。因此,如果我想为构建3执行此操作,它将包括#s 1和4(因为它们位于构建3中)以及3,因为它关闭了构建3(1)中的错误。
我以为我很接近:
SELECT stat.bug_num,
stat.build_id
FROM bug_status stat
JOIN bug_status stat2
ON stat2.closed_to = stat.bug_num
WHERE stat.build_id = 3;
......但它似乎没有给我想要的结果。谢谢你的帮助!
答案 0 :(得分:2)
您没有在WHERE子句中包含stat2.build_id
(我认为您的ON
列取自错误的表格):
SELECT stat.bug_num, stat.build_id
FROM bug_status stat
LEFT JOIN bug_status stat2
ON stat.closed_to = stat2.bug_num
WHERE stat.build_id = 3 OR stat2.build_id = 3
答案 1 :(得分:2)
SELECT stat.bug_num,
stat.build_id
FROM bug_status stat
WHERE stat.build_id = 3
OR stat.closed_to IN
( SELECT stat2.bug_num
FROM bug_status stat2
WHERE stat2.build_id = 3
)
;
(也可以通过JOIN或JOIN和UNION来实现,但我相信以上是最直观的方法。)
编辑添加:这是一个MySQL成绩单,展示了上述内容:
mysql> create table bug_status
-> (bug_num numeric, build_id numeric, closed_to numeric);
Query OK, 0 rows affected (0.01 sec)
mysql> insert into bug_status values (1, 3, null);
Query OK, 1 row affected (0.00 sec)
mysql> insert into bug_status values (2, 4, null);
Query OK, 1 row affected (0.01 sec)
mysql> insert into bug_status values (3, null, 1);
Query OK, 1 row affected (0.00 sec)
mysql> insert into bug_status values (4, 3, null);
Query OK, 1 row affected (0.00 sec)
mysql> insert into bug_status values (5, null, 2);
Query OK, 1 row affected (0.00 sec)
mysql> SELECT stat.bug_num,
-> stat.build_id
-> FROM bug_status stat
-> WHERE stat.build_id = 3
-> OR stat.closed_to IN
-> ( SELECT stat2.bug_num
-> FROM bug_status stat2
-> WHERE stat2.build_id = 3
-> )
-> ;
+---------+----------+
| bug_num | build_id |
+---------+----------+
| 1 | 3 |
| 3 | NULL |
| 4 | 3 |
+---------+----------+
3 rows in set (0.00 sec)
已编辑添加,因为IN (...)
方法在OP版本的MySQL中似乎不起作用:以下是另一种提供相同结果的查询:
SELECT stat.bug_num,
stat.build_id
FROM bug_status stat
LEFT
OUTER
JOIN bug_status stat2
ON stat.closed_to = stat2.bug_num
WHERE stat.build_id = 3
OR stat2.build_id = 3
;
答案 2 :(得分:0)
为什么不:
DECLARE @build_id int = <the build id>
SELECT stat.bug_num, stat.build_id, stat.closed_to
FROM bug_status stat
WHERE stat.build_id = @build_id
OR stat.closed_to = @build_id
?
答案 3 :(得分:0)
此查询...
SELECT *
FROM bug_status t1
WHERE
build_id = 3
OR EXISTS (
SELECT *
FROM bug_status t2
WHERE
t2.build_id = 3
AND t1.closed_to = t2.bug_num
)
...产生以下结果:
bug_num build_id closed_to
1 3 NULL
3 NULL 1
4 3 NULL
用简单的英语:选择行:
build_id = 3
build_id = 3
相关联的行。