簡體   English   中英

基於一個表聯接2個表

[英]Join 2 tables based on a single table

我似乎無法獲得所需的聯接/查詢!

可以說我有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"

...但是可以像我希望的那樣工作:)我可以接近,但是會有更多沒有正確訪問類型的用戶。

使用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"

也許:

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

干杯

嘗試

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

不確定您的“訪問”字段是否可以為空?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM