简体   繁体   中英

How to optimize SQL query more?

First at all i am nood into SQL thing, Now i am working on a class project where I have some tables like

Table user

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

Table Friend

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

Table Follow

user_id   |  follows
  1       |   99
  7       |   34

Table post

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

Now i want to get post by users friend and who he follows and offcourse his so i made this 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

this query works just fine. I just wanted to know is there anymore optimization could be done? Then how? Please teach me :)

Instead of using IN try it with JOIN add add few more indexes .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM