我正在开发一个新项目。我需要一个mysql查询的帮助,我认为它很慢。
SELECT post_id, user_id, content, title, TIME, (
SELECT username
FROM users
WHERE id = posts.user_id
) AS username
FROM posts
WHERE user_id =1
OR user_id
IN (
SELECT DISTINCT user_to
FROM friends
WHERE user_from =1
OR user_to =1
)
ORDER BY posts.post_id DESC
LIMIT 0 , 10
感谢您的帮助。
答案 0 :(得分:4)
您可以使用INNER JOIN
查询
SELECT a.post_id, a.user_id, a.content, a,title, a.TIME, b.username
FROM posts a
INNER JOIN users b
ON a.user_id = b.id
WHERE a.user_id =1
OR a.user_id
IN (
SELECT DISTINCT user_to
FROM friends
WHERE user_from =1
OR user_to =1
)
ORDER BY a.post_id DESC
LIMIT 0 , 10
这应该比您的实际查询更快。
答案 1 :(得分:4)
试试这个 -
SELECT
p.post_id
, p.user_id
, p.content
, p.title
, p.`time`
, u.username
FROM posts AS p
/*LEFT*/ JOIN users AS u ON u.ID = p.user_id
WHERE user_id = 1
OR user_id IN (
SELECT DISTINCT user_to
FROM friends
WHERE user_from = 1
OR user_to = 1
)
ORDER BY p.post_id DESC
LIMIT 0, 10
答案 2 :(得分:2)
尝试:
SELECT p.post_id, p.user_id, p.content, p.title, p.TIME, u.username
FROM (select distinct us.*
from friends f
join users us on f.user_to = us.id
WHERE f.user_from =1 OR f.user_to =1) u
JOIN posts p on u.id = p.user_id
ORDER BY p.post_id DESC
LIMIT 0 , 10