第三表内连接

时间:2012-03-30 09:20:50

标签: sql database

我使用内部联接检索带有两个表的数据。这是sql:

SELECT   mc.user_id, mc.id AS movie_comment_id, mc.add_date, 
         mc.movie_id, mc.comment, m.id, m.name 
FROM     movie_comment AS mc 
         INNER JOIN movie AS m ON m.id = mc.movie_id 
WHERE    movie_id = 1500 
AND      stat = 'onayli' 
ORDER BY mc.add_date DESC 
LIMIT 10

我想要的是从用户表中重新获取用户名。我写了这个sql但是不起作用

SELECT    u.id, u.username, mc.user_id, mc.id AS movie_comment_id, mc.add_date,
          mc.movie_id, mc.comment, m.id, m.name 
FROM      movie_comment AS mc 
          INNER JOIN movie AS m ON m.id = mc.movie_id 
                                ON mc.user_id = u.id 
WHERE     movie_id = 1500  
AND       stat = 'onayli' 
ORDER BY  mc.add_date DESC 
LIMIT 10

我如何检索用户名?

3 个答案:

答案 0 :(得分:3)

您需要在每个内部联接的开头指定INNER JOIN

select  u.ID ,u.USERNAME,mc.USER_ID,mc.ID as Movie_Comment_ID,mc.ADD_DATE,mc.MOVIE_ID,mc.COMMENT,m.ID,m.NAME
from MOVIE_COMMENT as mc
INNER Join MOVIE as m ON  m.ID=mc.MOVIE_ID 
INNER JOIN [USER] u ON mc.USER_ID = u.ID
WHERE MOVIE_ID = 1500  and STAT='onayli' ORDER BY mc.ADD_DATE DESC LIMIT 10

答案 1 :(得分:1)

select  u.ID ,u.USERNAME,mc.USER_ID,mc.ID as Movie_Comment_ID,mc.ADD_DATE,mc.MOVIE_ID,mc.COMMENT,m.ID,m.NAME
 from MOVIE_COMMENT as mc 
INNER Join MOVIE as m ON  m.ID=mc.MOVIE_ID 
INNER JOIN usertable as u ON mc.USER_ID = u.ID 
WHERE MOVIE_ID = 1500  and STAT='onayli' ORDER BY mc.ADD_DATE DESC LIMIT 10

答案 2 :(得分:0)

SELECT  u.ID,
u.USERNAME,
mc.USER_ID,
mc.ID as Movie_Comment_ID,
mc.ADD_DATE,
mc.MOVIE_ID,
mc.COMMENT,
m.ID,
m.NAME
FROM MOVIE_COMMENT as mc 
INNER JOIN MOVIE as m ON  m.ID = mc.MOVIE_ID 
INNER JOIN [User] u ON u.ID = mc.USER_ID 
WHERE MOVIE_ID = 1500  and STAT='onayli' ORDER BY mc.ADD_DATE DESC LIMIT 10