1

首先,我对 SQL 很感兴趣,现在我正在做一个类项目,其中有一些表,例如

表用户

user_id  |  username | name 
   1     |    nihan  |  Nihan Dip
   2     |     dip   |  Meaw ghew
  more   |  more     | more

桌友

you    | friend_id  
 1     |    2
 1     |    27
 2     |    9
 more  |   more

表跟随

user_id   |  follows
  1       |   99
  7       |   34

桌柱

post_id   |  user_id  | type  |  content  | post_time
  1       |   1       |  text | loren toren | timestamp
  2       |   2       | text  | ipsum       | timestamp

现在我想得到用户朋友的帖子以及他关注的人并离开他的人所以我做了这个SQL

SELECT 
    username, name,content, post_time
FROM
    post
        INNER JOIN
    user ON user.user_id = post.user_id
WHERE
    post.user_id IN (SELECT 
            friend_id
        FROM
            friend
        WHERE
            you = 1 

        UNION ALL 

        SELECT 
            follows
        FROM
            follow
        WHERE
            user_id = 1)
        OR post.user_id = 1
ORDER BY post_time DESC
LIMIT 10

这个查询工作得很好。我只是想知道是否可以进行更多优化?那怎么办?请教我 :)

4

1 回答 1

2

而不是使用INtry it with JOINadd add some more index

SELECT  DISTINCT u.name, u.username,
        p.content, p.post_time
FROM    post p
        INNER JOIN user u
            ON u.user_id = p.user_id
        INNER JOIN
        (
            SELECT  friend_id id
            FROM    friend
            WHERE   you = 1 
            UNION ALL 
            SELECT  follows id
            FROM follow
            WHERE user_id = 1
        ) s ON p.user_id = s.ID
ORDER BY post_time DESC
LIMIT 10
于 2013-09-14T13:29:13.057 回答