查询以获取列的差异

时间:2012-08-09 14:59:57

标签: php mysql join

我有两个主键为“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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

使用 NOT EXISTS

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