mysql查询一个表中的WHERE而不是另一个表

时间:2010-09-15 16:56:59

标签: sql mysql

编辑:这样做了:

  SELECT DISTINCT profileid 
FROM profilesrelevation 
WHERE profileid NOT IN (
  SELECT profileid FROM profiles
)

我需要获取profilesrelevation表中存在但不在配置文件表

中的profileid值

profile表有8107个不同的“profileid”值,而profilesrelevation表有8380个不同的“profilesid”值......

profiles.profileid
profilesrelevation.profileid

select * from profiles, profilesrelevation 
where profilesrelevation.profileid != profiles.profileid  

无效,怎么办?

3 个答案:

答案 0 :(得分:10)

使用LEFT JOIN / IS NULL

   SELECT pr.*
     FROM PROFILESREVELATION pr
LEFT JOIN PROFILES ON p.profileid = pr.profileid
    WHERE p.profileid IS NULL

使用NOT EXISTS

SELECT pr.*
  FROM PROFILESREVELATION pr
 WHERE NOT EXISTS(SELECT NULL
                    FROM PROFILES p
                   WHERE p.profileid = pr.profileid)

使用NOT IN

SELECT pr.*
  FROM PROFILESREVELATION pr
 WHERE pr.profileid NOT IN (SELECT p.profileid
                              FROM PROFILES p)

结论

LEFT JOIN IS NULL is the most efficient on MySQL when the columns compared are not nullable。如果是the columns compared were nullable, NOT IN and NOT EXISTS are more efficient

答案 1 :(得分:3)

你想要使用一套:

SELECT DISTINCT profileid 
FROM profilesrelevation 
WHERE profileid NOT IN (
  SELECT profileid FROM profiles
)

这将从table:profilesrelevation中选择行profileid不在table:profiles的所有行/列:)

更新:包含distinct,因为它会显示{id}在profilesrelevation表中不唯一。

答案 2 :(得分:0)

SELECT
    profilesrelevation.profileid
FROM
    profilesrelevation
    LEFT JOIN profiles ON profilesrelevation.profileid = profiles.profileid
WHERE
    profiles.profileid IS NULL

(您可能希望使用SELECT DISTINCT。)