将列与另一列进行比较

时间:2015-01-05 13:35:51

标签: mysql sql select join

deliverable_id deliverable_title deliverable_desc adviser_id passed_user deliverable_passed flag
             1 SRS               kogtong                   1           0                  0    0
             2 WEBSITE           Lorem ipsum...            1           0                  0    0
             3 system            asdsadasdasdasd           1           0                  0    0
             4 software          sdgdThyiliul234           1           0                  0    0
             5 NULL              NULL                      1           4                  1    1
             6 NULL              NULL                      1           4                  2    1

我想创建一个可以比较deliverable_passed是否与deliverable_id相同的查询。如果它们相同,则不会打印相同的deliverable_id

这是我目前的查询是:

SELECT * FROM deliverable
WHERE deliverable_id!=deliverable_passed

当前输出(基于deliverable_id):1 2 3 4

比较后我的预期输出将是(基于deliverable_id):3 4

由于deliverable_passed值为1& 2已经存在。

3 个答案:

答案 0 :(得分:1)

这样做你想要的吗?

select d.*
from deliverable d
where exists (select 1 from deliverable d2 where d2.id = d.deliverable_passed) or
      exists (select 1 from deliverable d2 where d2.deliverable_passed = d.id);

答案 1 :(得分:1)

使用自我加入检查已通过的可交付成果。

试试这个:

SELECT d1.* 
FROM deliverable d1 
LEFT OUTER JOIN deliverable d2 ON d2.deliverable_id = d1.deliverable_passed
WHERE d2.deliverable_id IS NULL

答案 2 :(得分:1)

您希望选择所有可交付件(具有标题),其中没有记录存在及其deliveryrable_passsed ID。所以使用NOT EXISTS:

SELECT * 
FROM deliverable
WHERE deliverable_title is not null
AND NOT EXISTS
(
  SELECT * FROM deliverable passed
  WHERE passed.deliverable_passed = deliverable.deliverable_id 
);

甚至更简单的NOT IN:

SELECT * 
FROM deliverable
WHERE deliverable_title is not null
AND deliverable_id NOT IN (SELECT deliverable_passed FROM deliverable);

(但是Aleks G是对的。这是一个糟糕的数据库设计,你应该改变它。)