查询从两个表中获取数据

时间:2012-05-07 11:56:22

标签: mysql

我有两张桌子

  

用户表

id fname lname
1  asdf  fdg
2  asd2  ddf 
3  xsss  ss
4  frfr  dd 
5  dede  dd

和userassociation表

user1 associateduser
1      2
1      3

我想从用户表中选择不应包含user1及其关联用户的id,fname,lname

2 个答案:

答案 0 :(得分:2)

也许是这样的:

SELECT
    id,
    fname,
    lname
FROM
    user
WHERE NOT EXISTS
    (
        SELECT
            NULL
        FROM
            userassociation
        WHERE
            userassociation.user1=user.id
            AND userassociation.associateduser=user.id
    )

答案 1 :(得分:0)

select id,fname,lname from `user`
where id not in (select user1 as u 
                 from userassociation 
                 union 
                 select associateduser as u 
                 from userassociation)