我有以下MySQL查询:我该如何重构这个MySQL查询?
(SELECT c.Channel as name, count(*) as total_episode
FROM (
SELECT a.aid, a.vid
FROM videoItem v INNER JOIN aid2vid a USING(vid)
GROUP BY a.aid
) a1 INNER JOIN channelListingItem c USING(aid)
GROUP BY c.Channel
)
UNION
(SELECT c1.Channel as name, 0 as total_episode
FROM channelListingItem c1 LEFT JOIN (
SELECT c.Channel FROM (
SELECT a.aid, a.vid
FROM videoItem v INNER JOIN aid2vid a USING(vid)
GROUP BY a.aid
) a1 INNER JOIN channelListingItem c USING(aid)
GROUP BY c.Channel
) c2 USING(Channel)
WHERE c2.Channel is null
GROUP BY name
);
基本上,这种说法确实是让每个通道正确的计数插曲&为渠道W/O VID在随后的表(videoItem)分配为零。
注意
SELECT a.aid, a.vid
FROM videoItem v
INNER JOIN aid2vid a USING(vid)
GROUP BY a.aid
被复制了两次,这说明MySQL的发言中,我没有看到MySQL的重复使用查询结果。
+----+--------------+------------+------+----------+---------+---------+----------+------+---------------------------------+
| id | select_type | table | type | pos_keys | key | key_len | ref | rows | Extra |
+----+--------------+------------+------+----------+---------+---------+----------+------+---------------------------------+
| 1 | PRIMARY | <derived2> | ALL | NULL | NULL | NULL | NULL | 313 | Using temporary; Using filesort |
| 1 | PRIMARY | c | ALL | idx_vid | NULL | NULL | NULL | 616 | Using where; Using join buffer |
| 2 | DERIVED | a | ALL | vid | NULL | NULL | NULL | 1015 | Using temporary; Using filesort |
| 2 | DERIVED | v | ref | idx_vid | idx_vid | 32 | db.a.vid | 10 | Using index |
| 3 | UNION | c1 | ALL | NULL | NULL | NULL | NULL | 616 | Using temporary; Using filesort |
| 3 | UNION | <derived4> | ALL | NULL | NULL | NULL | NULL | 28 | Using where; Not exists |
| 4 | DERIVED | <derived5> | ALL | NULL | NULL | NULL | NULL | 313 | Using temporary; Using filesort |
| 4 | DERIVED | c | ALL | idx_vid | NULL | NULL | NULL | 616 | Using where; Using join buffer |
| 5 | DERIVED | a | ALL | vid | NULL | NULL | NULL | 1015 | Using temporary; Using filesort |
| 5 | DERIVED | v | ref | idx_vid | idx_vid | 32 | db.a.vid | 10 | Using index |
|NULL| UNION RESULT | <union1,3> | ALL | NULL | NULL | NULL | NULL | NULL | |
+----+--------------+------------+------+----------+---------+---------+----------+------+---------------------------------+
11 rows in set (0.02 sec)
我该如何重构这个MySQL语句? MySQL语句中还有不错的重构工具吗?
谢谢。
它有什么问题?你为什么要重构? – 2012-01-04 07:18:18
你可以尝试Toad for Mysql工具,它是免费的。 – rkosegi 2012-01-04 07:18:26
@SergioTulentsev:解释附加的结果。 – user1045217 2012-01-04 08:09:24