1

我有两个表,主键为“poll_id”,每个表中的列名为“object_id”。我无法从 t1 中获取 t2 中不存在且带有 poll_id (主键)的对象。

       T1                           T2

poll_id|object_id            poll_id|object_id
1      | 2                    1     |  2
1      | 3                          |

我需要得到[poll_id]=>1,[object_id]=>3

4

2 回答 2

2

尝试

select t1.* from t1 
left join t2 on t1.poll_id = t2.poll_id and t1.object_id = t2.object_id
where t2.object_id is null
于 2012-08-09T15:02:30.120 回答
2

使用不存在

SELECT poll_id, object_id
FROM t1
WHERE NOT EXISTS
      ( SELECT *
        FROM t2
        WHERE t2.poll_id = t1.poll_id
          AND t2.object_id = t1.object_id
      ) 
  AND poll_id = 1 ;                        -- additional requirement

使用LEFT JOIN / IS NULL

SELECT t1.poll_id, t1.object_id
FROM t1
  LEFT JOIN t2
    ON  t2.poll_id = t1.poll_id
    AND t2.object_id = t1.object_id
WHERE t2.object_id IS NULL 
  AND t1.poll_id = 1 ;                        -- additional requirement

使用NOT IN

SELECT poll_id, object_id
FROM t1
WHERE (poll_id, object_id) NOT IN
      ( SELECT poll_id, object_id
        FROM t2
      ) 
  AND poll_id = 1 ;                        -- additional requirement
于 2012-08-09T15:07:33.337 回答