什么mysql查询更好?

时间:2010-09-22 10:26:44

标签: mysql performance select

我有2个mysql查询,检索相同的数据?,您认为哪个更好用,为什么?考虑到标准,更好的代码等对不起,如果这是一个愚蠢的问题,但我是一个好奇的猫!所以这里:

QUERY 1:

SELECT *
FROM
((
  SELECT u.username, u.picture, m.id, m.user_note, m.reply_id, m.reply_name, m.dt
  FROM   relationships r
  JOIN   notes m ON m.user_id = r.leader
  JOIN   user u ON r.leader = u.user_id
  WHERE  r.listener ='2'
)
UNION ALL
(
  SELECT u.username, u.picture, m.id, m.user_note, m.reply_id, m.reply_name, m.dt
  FROM   notes m
  JOIN   user u ON m.user_id = u.user_id
  WHERE  u.user_id ='2'
)) d
WHERE    d.dt < '2010-09-20_131830'
ORDER BY d.dt DESC

QUERY 2:

SELECT u.username, u.picture, m.id, m.user_note, m.reply_id, m.reply_name, m.dt
FROM notes m
INNER JOIN user u
ON m.user_id = u.user_id
WHERE (m.user_id = '2'
OR m.user_id IN (
   SELECT r.leader
   FROM relationships r
   WHERE r.listener ='2'))
AND dt < '2010-09-20_131830'
ORDER BY dt DESC

1 个答案:

答案 0 :(得分:2)

我发现UNION ALL版本更容易理解(可能是我的情况)但我会重写如下。

AND m.dt < '2010-09-20_131830添加到每个部分应该会给您带来更好的表现 您可以运行几次并验证它是否有所作为。

SELECT  u.username
        , u.picture
        , m.id
        , m.user_note
        , m.reply_id
        , m.reply_name
        , m.dt 
FROM    relationships r 
        INNER JOIN notes m ON m.user_id = r.leader 
        INNER JOIN user u ON r.leader = u.user_id 
WHERE   r.listener ='2' 
        AND m.dt < '2010-09-20_131830' 
UNION ALL 
SELECT  u.username
        , u.picture
        , m.id
        , m.user_note
        , m.reply_id
        , m.reply_name
        , m.dt 
FROM    notes m 
        INNER JOIN user u ON m.user_id = u.user_id 
WHERE   u.user_id ='2' 
        AND m.dt < '2010-09-20_131830' 
ORDER BY m.dt DESC