返回用户没有的ID

时间:2014-06-02 21:44:43

标签: php mysql

我有两个数据库表。一个是egl_achievement,另一个是egl_achievement_member。一个只有成就,另一个有成就的成员。我试图编写一个查询,返回会员所没有的所有成就。我以为我可以使用MINUS,但是mysql不支持。

SELECT egl_achievement.id as id FROM egl_achievement LEFT JOIN egl_achievement_member ON egl_achievement.id = egl_achievement_member.egl_achievement_id WHERE egl_achievement_member.member_id =57;

这显然会返回成员57所拥有的ID,但我怎么能得到反面呢?

3 个答案:

答案 0 :(得分:3)

您可以使用包含所有成就的子选择,然后列出未包含的成就:

SELECT egl_achievement.id as id
FROM egl_achievement
WHERE egl_achievement.id NOT IN(
    SELECT egl_achievement_member.egl_achievement_id
    FROM egl_achievement_member
    WHERE egl_achievement_member.member_id =57);

答案 1 :(得分:0)

你应该可以使用NOT IN。 这应该选择成员57没有的所有不同的id。

select distinct eql_achievement.id as id
from eql_achievement where eql_achievement.id not in
 (SELECT egl_achievement_member.eql_achievement_id as id FROM egl_achievement_member
WHERE egl_achievement_member.member_id =57;)

答案 2 :(得分:0)

右连接并过滤没有id的那些(那些未在A表中定义的那些)

SELECT * FROM `egl_achievement_member` `a` 
RIGHT JOIN `egl_achievement` `b` 
ON `a`.`achievement_id` = `b`.`id` 
WHERE `a`.`achievement_id` IS NULL

然后与用户

SELECT * FROM `egl_achievement_member` `a` 
RIGHT JOIN `egl_achievement` `b` 
ON `a`.`member_id` = 57 
AND `a`.`achievement_id` = `b`.`id` 
WHERE `a`.`achievement_id` IS NULL

这是一个非常甜蜜的时间表

SQL Joins