检索特定列值的联合表中ID没有值的值

时间:2017-02-08 16:17:06

标签: mysql

我知道,这个问题标题并不吸引人,但用一句话来解释是非常棘手的,所以这就是我在2个表中的内容。

Table 1

ID    other_id
1     1
2     1
3     2

Table 2
ID    parent_id    attribute_id    value
54    1            125             jiazdjdaz
55    1            367             5
58    2            125             zdvgbdajz
59    2            367             4
71    3            125             hagvbadd

t2.parent_id等于t1.ID

我希望能够检索“other_id”2,因为对于属性367,它在表T2中没有值。

我怎样才能轻松做到?

1 个答案:

答案 0 :(得分:2)

你想要的是存在量化,一种存在的测试。在SQL中,使用EXISTS

select other_id from T1 
where not exists ( 
    select 1 from T2 
    where T1.ID = T2.parent_id
    and attribute_id = 367
)

有多种方法可以做到这一点。您还将在Web上看到使用外连接的解决方案,在内部表上测试NULL。并且您会发现相关子查询的指控很慢,这取决于DBMS。希望这至少可以为您提供一个起点。