我编写了以下查询(从字符串常量放在一起的重复部分),它们尝试在共享日历应用程序中执行以下操作。
status_relation
default_status_relation
状态不等于0的所有用户。如果status_relation
中没有任何内容,则会提供默认的每周状态。目前查询有效(使用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 )
答案 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上做同样的事情