0

I have three tables

USER
---------------------------------------
id | uid | first_name | last_name | ...
---------------------------------------
0  | 95  | ...        | ...       | ...   
1  | 100 | ...        | ...       | ...     
2  | 120 | ...        | ...       | ...
3  | 130 | ...        | ...       | ...

NEWS_mm
------------------------
uid_local | uid_foreign 
------------------------
40        | 90        
40        | 100 
50        | 120 
50        | 130

NEWS
-------------------------------
id | uid  | title | image | ...
-------------------------------
0  | 40   | ...   | ...   | ...    
1  | 50   | ...   | ...   | ...
2  | 60   | ...   | ...   | ...

Now i want only select all users from table "USER" which have the news id 50 from table "NEWS". NEWS_mm has the news id (id_local) from "NEWS" and the user id (id_foreign) from "USER"

SELECT USER.*, NEWS_MM.*, NEWS.*
FROM USER
    JOIN NEWS_MM
        ON NEWS_MM.uid_foreign = USER.uid
    JOIN NEWS
        ON NEWS_MM.uid_local = NEWS_MM.uid_local
WHERE NEWS.uid = 50 
4

1 回答 1

2

您在正确的行上,但是您正在 NEWS_MM = NEWS_MM 上加入表 NEWS 我怀疑您想像这样加入:

SELECT USER.*, NEWS_MM.*, NEWS.*
FROM USER
JOIN NEWS_MM
    ON NEWS_MM.uid_foreign = USER.uid
JOIN NEWS
    ON NEWS_MM.uid_local = NEWS.uid
WHERE NEWS.uid = 50  

另请注意,您知道 NEWS_MM.uid_local 的值与 NEWS.uid 相同,因此如果您只想要来自 USER 表的数据,那么您实际上根本不需要第二次连接,这应该会提供更好的性能

SELECT 
  NEWS_MM.uid_local, 
  USER.* 
FROM USER
  JOIN NEWS_MM
    ON NEWS_MM.uid_foreign = USER.uid
WHERE NEWS_MM.uid_local = 50  
于 2013-06-09T10:53:31.553 回答