mysql:请帮我摆脱嵌套子句

时间:2012-03-20 14:56:10

标签: mysql

我编写了以下查询(从字符串常量放在一起的重复部分),它们尝试在共享日历应用程序中执行以下操作。

  • 在当前日期+时间
  • 搜索状态不等于0的所有用户status_relation
  • 在当前工作日+时间搜索default_status_relation状态不等于0的所有用户。如果status_relation中没有任何内容,则会提供默认的每周状态。
  • 全外加入两个
  • 然后从userid
  • 加入用户名
  • 然后由php处理,这将显示当天所有具有状态!= 0的用户的状态(或默认状态,如果状态不存在)。
  • php需要知道它是返回状态还是默认状态

目前查询有效(使用UNION来模拟外部联接)。但是,我想优化它 - 我知道删除子查询可能会有所帮助。怎么办?

SELECT q.*,
   users.username,
   users.userid AS uid
FROM   (SELECT *
    FROM   ((SELECT sr.status   AS srstatus,
                    dsr.status  AS dsrstatus,
                    sr.userid   AS sruserid,
                    dsr.userid  AS dsruserid
             FROM   (SELECT *
                     FROM   status_relation
                     WHERE  DATE = '2012-03-19'
                            AND TIME = '0'
                    ) sr
             LEFT JOIN 
                    (SELECT *
                     FROM   default_status_relation
                     WHERE  weekday = '0'
                     AND TIME = '0') 
                    ) dsr
             ON sr.userid = dsr.userid)
          UNION
            (SELECT sr.status   AS srstatus,
                    dsr.status  AS dsrstatus,
                    sr.userid   AS sruserid,
                    dsr.userid  AS dsruserid
             FROM   (SELECT *
                     FROM   status_relation
                     WHERE  DATE = '2012-03-19'
                            AND TIME = '0') sr
                    RIGHT JOIN (SELECT *
                                FROM   default_status_relation
                                WHERE  weekday = '0'
                                       AND TIME = '0') dsr
                      ON sr.userid = dsr.userid)
       ) myjoin
    WHERE  ( ( sruserid IS NOT NULL
               AND srstatus != '0' )
              OR ( sruserid IS NULL
                   AND dsrstatus != '0' ) )) q
   LEFT JOIN users
     ON ( q.sruserid = users.userid
           OR q.dsruserid = users.userid )  

1 个答案:

答案 0 :(得分:0)

您应该可以替换此部分:

(SELECT sr.status   AS srstatus,
    dsr.status  AS dsrstatus,
    sr.userid   AS sruserid,
    dsr.userid  AS dsruserid
 FROM   (SELECT *
         FROM   status_relation
         WHERE  DATE = '2012-03-19'
             AND TIME = '0'
        ) sr
LEFT JOIN 
    (SELECT *
    FROM   default_status_relation
    WHERE  weekday = '0'
        AND TIME = '0') 
    ) dsr
ON sr.userid = dsr.userid)

通过

SELECT sr.status   AS srstatus,
    dsr.status  AS dsrstatus,
    sr.userid   AS sruserid,
    dsr.userid  AS dsruserid
 FROM status_relation sr
 left join default_status_relation dsr
   ON sr.userid = dsr.userid and 
       sr.date = '2012-03-19' and 
       sr.time = TIME = '0' and
       dsr.weekday = 0 and 
       dsr.time = 0;

你可以在UNION上做同样的事情