简体   繁体   English

MySQL - 使用关系表加入

[英]MySQL - JOIN with relation table

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". 现在我只想从表“USER”中选择所有用户,其中包含来自表“NEWS”的新闻ID 50。 NEWS_mm has the news id (id_local) from "NEWS" and the user id (id_foreign) from "USER" 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 

you are on the right lines but you are joining the table NEWS on NEWS_MM = NEWS_MM I suspect you want to join like so: 你是在正确的行,但你加入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  

also note that you know that the value of NEWS_MM.uid_local is the same as NEWS.uid so you don't actually need the second join at all if you only want the data from the USER table which should give better performance 另请注意,您知道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  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM