SQL 连接两个 ID 匹配的表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26827522/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 02:55:43  来源:igfitidea点击:

SQL join two tables where IDs match

sqljointable

提问by Ashley Williams

I have two tables in my database.

我的数据库中有两个表。

Moviestable:

Movies桌子:

+----------------------------------------
| ID | title                | timestamp |
+----------------------------------------
| 1  | The host             | time      |
| 2  | Fight Club           | time      |
| 4  | 21                   | time      |
----------------------------------------+

Movie_Linkstable:

Movie_Links桌子:

+---------------------------------------+
| ID | link                 | movie_id  |
+---------------------------------------+
| 1  | some link            | 1         |
| 2  | some link            | 1         |
| 3  | some link            | 1         |
+---------------------------------------+

At the moment I am only selecting the rows from the Moviestable where the titleis like for example:

目前我只从Movies表中选择行title,例如:

SELECT * FROM `Movies` 
WHERE `title` LIKE '%The Host%' 
ORDER BY `timestamp` DESC DESC LIMIT 30

But what I want to do is the same query as above but join Movie_Linkstable where movie_idequals Moviestable's IDand get all links that have a Movie_idequal to 1.

但我想要做的是与上面相同的查询,但连接Movie_Links表,其中movie_id等于Movies表的ID并获取所有具有Movie_id等于1.

回答by Ali Al-arnous

Test the following query :

测试以下查询:

SELECT ml.id,m.title,m.timestamp, ml.link
FROM movies m ,Movie_Links ml
WHERE m.id=ml.movie_id and title LIKE '%The Host%'

BR,

BR,

回答by Tufayal Hossin Emon

SQL join two tables With IDs match

SQL 连接两个 ID 匹配的表

SELECT *
FROM Movies 
LEFT JOIN Movie_Links 
ON Movies.ID = Movie_Links.movie_id;

回答by artm

Just join on the matching columns:

只需加入匹配的列:

SELECT * FROM movies m
JOIN MovieLinks ml
ON ml.movie_id = m.id
WHERE m.title LIKE '%The Host%' 

回答by SMA

Try join (removed order by clause as i dont see those fields in above question):

尝试加入(删除 order by 子句,因为我没有看到上述问题中的那些字段):

SELECT m.*, ml.link 
FROM movies m join Movie_Links ml
ON   m.id = ml.movie_id 
WHERE m.title LIKE '%The Host%' 
AND   m.id = 1
AND   ml.id = 1
--ORDER BY `featured` DESC,`date_added` DESC,`released` DESC LIMIT 30

回答by NSimon

You could try something like this for a join :

你可以尝试这样的加入:

SELECT * FROM 'movies'
WHERE 'title" LIKE '%The Host%'
AND Movies.id = Links.id
AND Links.id = 1
ORDER BY 'featured' DESC, 'date_added' DESC, 'released' DESC LIMIT 30