3

我正在开发一个新项目。我需要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 

谢谢你的帮助。

4

3 回答 3

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 

这应该比您的实际查询更快。

于 2013-06-11T07:27:30.597 回答
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 
于 2013-06-11T07:28:05.957 回答
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 
于 2013-06-11T09:10:30.237 回答