Mysql查询根据条件选择名称

时间:2011-10-04 22:29:54

标签: mysql

Users             UserGroup

id  name      rowid    GrpID   UserID   name
1   aaa         1        1      1        aaa
2   bbb         2        1      3        ccc
3   ccc         3        2      1        aaa
4   ddd         4        2      4        ddd
5   eee         5        2      5        eee

我有2个表,用户和用户组,我想显示用户表中的所有名称,但除了userGroup表中与GrpID相关联的userID之外。

for grpID 1 i want to display
bbb
ddd
eee

我不想显示用户ID 2和3,因为它在grpID 1中。我将有很多grpID。怎么在我的SQL中做到这一点。我不想显示已经在GrpID 1的UserGroup表中的名称..和其他GroupID的相同条件

4 个答案:

答案 0 :(得分:1)

怎么样?

select name from users u
where u.id not in (
    select userid from usergroup ug
    where ug.grpid = 1)

答案 1 :(得分:0)

Select * from users where userid <> '1'

As&lt;&gt;意思是:不是

答案 2 :(得分:0)

加入你的SQL中的表。

Ansi加入(类似这样):

select
  user.id,
  user.name
from
  user
  inner join usergroup on user.id = usergroup.rowid
where
  usergroup.grpid = __parameter goes here__

Oldschool加入(通过where子句):

select
  user.id,
  user.name
from
  user,
  usergroup
where
  user.id = usergroup.rowid and
  usergroup.grpid = __parameter goes here__

答案 3 :(得分:0)

    select users.name from users, usergroup where  users.userid = usergroup.userid and usergroup.grpid <> :grpId