查询columnA!= columnB的不同值

时间:2015-10-17 10:39:11

标签: mysql

我试图选择ID = '12-027-013'不属于的群组的group_ID。

我试过了这个问题。

SELECT DISTINCT groups.group_ID, groups.group_name 
FROM groups INNER JOIN group_member 
ON groups.group_ID = group_member.group_ID 
WHERE groups.group_name LIKE "%e%" 
AND group_member.ID != "12-027-013"

但它仍会显示ID = '12-027-013'已经成为其中一部分的群组。

这些是我的表

表:群组

enter image description here

表: group_member

enter image description here

这是我的查询结果

enter image description here

非常感谢任何帮助。谢谢。

3 个答案:

答案 0 :(得分:1)

试试这个

SELECT DISTINCT
  groups.group_ID,
  groups.group_name
FROM groups
  INNER JOIN group_member
    ON groups.group_ID = group_member.group_ID
  LEFT OUTER JOIN (SELECT group_id FROM group_member WHERE group_member.ID = "12-027-013") gm ON group_member.group_id=gm.group_id
WHERE groups.group_name LIKE "%e%"
  AND gm.group_id IS null

答案 1 :(得分:1)

我认为最好的方法只是LEFT JOIN

SELECT g.group_ID, g.group_name 
FROM groups g LEFT JOIN
     group_member gm
     ON gm.group_ID = g.group_ID  AND
        gm.ID = '12-027-013'
WHERE g.group_name LIKE '%e%' AND
      gm.group_ID IS NULL;

这没有DISTINCT,因此它应该比原始查询执行得更好。

类似的替代方案是NOT EXISTS

SELECT g.*
FROM groups g 
WHERE g.group_name LIKE '%e%' AND
      NOT EXISTS (SELECT 1
                  FROM group_member gm
                  WHERE gm.group_ID = g.group_ID  AND
                        gm.ID = '12-027-013'
                 );

这两个版本都可以使用groups(group_name, group_id)group_member(group_id, id)上的索引来获得最佳效果。

答案 2 :(得分:0)

试试这个:

SELECT DISTINCT groups.group_ID, groups.group_name 
FROM groups INNER JOIN group_member 
ON groups.group_ID = group_member.group_ID 
WHERE groups.group_name LIKE "%e%" 
AND group_member.ID NOT LIKE "%12-027-013%" //if the type of id is text

问题在于“!=”。它应该不是