首先,我很想进入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
这个查询工作得很好。我只是想知道是否还有优化可以完成?那怎么样?请教我:)
答案 0 :(得分:2)
而不是使用IN
尝试使用JOIN
添加添加更多索引。
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