0

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

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

4 回答 4

2

You can use NOT IN in a WHERE clause:

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

See SQL Fiddle with Demo

于 2012-11-06T14:23:58.790 回答
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
于 2012-11-06T14:19:26.553 回答
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
于 2012-11-06T14:19:08.767 回答
0

我不太明白你的意思,但是对于 SQL 中的布尔值:

SELECT * FROM table WHERE attr_id <> '14'

而不是=你使用的“相等”的意思,<>或者!=两者都表示“不同”的意思(第一个得到更好的支持,但几乎无关紧要);

于 2012-11-06T14:21:49.947 回答