我有三张桌子
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 | ... | ... | ...
现在我只想从表“USER”中选择所有用户,其中新闻ID为表“NEWS”。 NEWS_mm包含来自“NEWS”的新闻ID(id_local)和来自“USER”的用户ID(id_foreign)
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
答案 0 :(得分:2)
你是在正确的路线,但你正在加入NEWS_MM = NEWS_MM上的新闻我怀疑你想加入这样的话:
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表中的数据,那么您实际上根本不需要第二次连接,这样可以提供更好的性能< / p>
SELECT
NEWS_MM.uid_local,
USER.*
FROM USER
JOIN NEWS_MM
ON NEWS_MM.uid_foreign = USER.uid
WHERE NEWS_MM.uid_local = 50