2010-11-29 66 views
2

我似乎无法获得我需要的连接/查询!根据单个表格加入2个表格

可以说我有3个表(修剪为这个职位...)

user_courses 
(int) user_id 
(int) course_id 

users 
(int) user_id 
(txt) name 
(txt) access 

courses 
(int) course_id 
(txt) course_desc 

我所试图做的是选择选择所有用户与正在采取具体课程有一定的接入类型(COURSE_ID )

像...

SELECT * 
FROM user_courses uc 
JOIN users u 
ON uc.user_id = u.user_id 
JOIN courses c 
ON uc.course_id = c.course_id 
WHERE u.access = "foobar" 

...但工作就像我希望它:) 我可以亲近,但有没有correc额外用户t访问类型。

+0

有什么问题?如果某些用户没有正确的访问类型,则需要在db中进行更改。 – hgulyan 2010-11-29 09:11:43

回答

1

使用inner join

SELECT * 
    FROM user_courses uc 
    INNER JOIN users u 
    ON uc.user_id = u.user_id 
    LEFT JOIN courses c 
    ON uc.course_id = c.course_id 
    WHERE u.access = "foobar" 
0

也许是:

select * from users u 
where u.access='foobar' 
    and exists (select 1 from user_courses uc where uc.user_id=u.user_id) 

干杯

0

尝试

... 
WHERE ISNULL(u.access, '') = 'foobar' 

不知道你的 '访问' 栏可以为空?