选择没有指定字段的行

时间:2012-11-06 14:13:39

标签: sql

我有一个包含以下字段的表:

object_id
attr_id
string_value

object_id引用另一个表中的对象,属性id也是如此(它们都是外键)。

所以例如我有这样的行:

22, 14, blah
22, 30, argh
22, 31, moo
44, 30, argh
44, 31, kaw

如您所见,对象44没有使用值设置属性14.

我想要做的是选择所有没有定义属性14的对象。

有没有人知道如何做到这一点?

4 个答案:

答案 0 :(得分:2)

您可以在NOT IN子句中使用WHERE

select *
from yourtable t1
where object_id not in (select object_id
                        from yourtable t2
                        where attr_id in (14))

请参阅SQL Fiddle with Demo

答案 1 :(得分:1)

假设您有3个表格,并且您不知道attr_id缺少什么

SELECT c.object_id
FROM 
    (
        SELECT  a.object_id, b.attr_id
        FROM    Table1 a CROSS JOIN Table2 b
    ) c LEFT JOIN tableName d
          ON c.object_id = d.object_id AND
              c.attr_id = d.attr_id
WHERE d.string_value IS NULL

但是如果要返回所有列,

SELECT e.*
FROM TableName e
      INNER JOIN
(
  SELECT c.object_id
  FROM 
      (
          SELECT  a.object_id, b.attr_id
          FROM    Table1 a CROSS JOIN Table2 b
      ) c LEFT JOIN tableName d
            ON c.object_id = d.object_id AND
                c.attr_id = d.attr_id
  WHERE d.string_value IS NULL
) f ON e.object_id = f.object_id

答案 2 :(得分:0)

select m.*
from MyTable m
where not exists (select 1 from MyTable m2 where m2.object_id = m.object_id and m2.attr_id = 14)

你也可以通过自我加入来实现,例如:

select m1.*
from MyTable m1
inner join MyTable m2 on m1.object_id = m2.object_id and m2.attr_id = 14
where m2.object_id is null

答案 3 :(得分:0)

我不太明白你的意思,但对于SQL中的布尔人来说:

SELECT * FROM table WHERE attr_id <> '14'

而不是=,这意味着“相等”,而是使用<>!=,这两者都意味着“不同”(第一个更好支持,但它几乎无关紧要); < / p>