合并表和查询

时间:2010-10-05 22:55:32

标签: mysql join

我的mysql架构中有这些表:

posts:

   ---------------------------------------------
   id|type | userid | title | msg | time_added

users:

   ------------------
   userid | username

如何只显示6个条目,其中:type是音频或视频,仅适用于某个用户名?

4 个答案:

答案 0 :(得分:2)

SELECT TOP 6 *
FROM posts
INNER JOIN users ON posts.userid = users.userid
WHERE type IN ('audio','video')
AND username = @username;

或(因为TOP可能只是MS SQL Server ......)

SELECT *
FROM posts
INNER JOIN users ON posts.userid = users.userid
WHERE type IN ('audio','video')
AND username = @username
LIMIT 6;

答案 1 :(得分:0)

Select title, msg, type
From Users Left Join Posts on Users.userid = Posts.userid
where type in ("audio", "video")
    and username = @username
limit 6

答案 2 :(得分:0)

这是一种方式:

SELECT TOP 6 
      P.id
     ,P.type
     ,P.userid
     ,U.username
     ,P.title
     ,P.msg
     ,P.time_added
 FROM posts P
   INNER JOIN users U ON U.userid = P.userid
 WHERE U.username = 'given user name'
    AND (P.type = 'audio' OR P.type = 'video')

答案 3 :(得分:0)

SELECT *
FROM posts p
INNER JOIN users u
  ON u.userid = p.userid
  AND u.username = 'name'
WHERE p.type IN ('audio','video')
ORDER BY time_added DESC
LIMIT 6