将列与另一列进行比较

Comparing column to another

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 已经存在。

这是你想要的吗?

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);

使用SELF JOIN检查传递的可交付成果。

试试这个:

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

您想要 select 所有没有记录 存在 的可交付成果(有标题)及其 deliverable_passed 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 是对的。这是一个糟糕的数据库设计,你应该改变它。)