如何根据相关表的结果选择MySQL记录?

时间:2013-08-24 05:28:06

标签: php mysql join

我在这个场景中有两个表:members和team_members。成员表非常自我解释。团队成员表存储成员的团队信息(如果他们是团队成员)。如果团队成员表中没有具有用户的member_id的行,则他们不在团队中。我想要做的是让所有不是团队成员的用户。我应该使用左连接,内连接,外连接还是只加入?这个查询会是什么样的?

CREATE TABLE IF NOT EXISTS `members` (
  `member_id` int(15) NOT NULL AUTO_INCREMENT,
  `group_id` int(15) NOT NULL,
  `display_name` text NOT NULL,
  `email_address` text NOT NULL,
  `password` text NOT NULL,
  `status` tinyint(1) NOT NULL,
  `activation_code` varchar(16) NOT NULL,
  `date_joined` text NOT NULL,
  PRIMARY KEY (`member_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS `team_members` (
  `team_member_id` int(15) NOT NULL AUTO_INCREMENT,
  `member_id` int(15) NOT NULL,
  `team_id` int(15) NOT NULL,
  `date_joined` text NOT NULL,
  `date_left` text NOT NULL,
  `total_xp` int(15) NOT NULL,
  PRIMARY KEY (`team_member_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;

2 个答案:

答案 0 :(得分:1)

有几种方法可以编写此查询。

对我而言,这是最容易阅读和理解的:

select * from members where member_id not in (select member_id from team_members).

这是一种非常简单的编写方式。如果你决定要一切,你可以快速注释掉where子句:

select m.* from members m left outer join team_members tm on m.member_id = tm.member_id
where tm.member_id is null

这种方式从我读过的SQL看起来并不常见,但我认为这很简单:

select m.* from members m where not exists
    (select member_id from team_members tm where tm.member_id = m.member_id)

答案 1 :(得分:0)

从表面上看,下面的查询很好

SELECT members.member_id 
FROM   members 
       LEFT OUTER JOIN team_members 
                    ON team_members.member_id = members.member_id 
WHERE  team_members.member_id IS NULL 

这样做,但在再次阅读您的问题时,您似乎有一个date_left列,如果您只想要那些尚未离开团队的成员那么

SELECT members.member_id 
FROM   members 
       LEFT OUTER JOIN (SELECT * 
                        FROM   team_members 
                        WHERE  team_members.date_left != '') CURRENT_TEAMS 
                    ON CURRENT_TEAMS.member_id = members.member_id 
WHERE  CURRENT_TEAMS.member_id IS NULL 

SQLFiddle示例 http://www.sqlfiddle.com/#!2/46b25/6/0