SQL连接两个ID匹配的表

时间:2014-11-09 11:08:34

标签: sql jointable

我的数据库中有两个表。

Movies表:

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

Movie_Links表:

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

目前我只选择Movies表中title所在的行:

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

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

5 个答案:

答案 0 :(得分:2)

测试以下查询:

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,

答案 1 :(得分:0)

只需加入匹配列:

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

答案 2 :(得分:0)

尝试加入(删除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

答案 3 :(得分:0)

你可以尝试这样的东西来加入:

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

答案 4 :(得分:0)

SQL连接两个ID匹配的表

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