有没有办法重写此查询以作为SQL视图

时间:2012-04-29 15:27:26

标签: mysql sql phpmyadmin

我设法写下面的查询,效果很好。我的问题是我多次使用它并且我认为它保证了自己的观点,但是当我让phpmyadmin为我创建视图时,过去花费0.0060秒的查询现在需要6.2094秒。

我的查询:

SELECT tr.uuid, tr.creator,
(
    SELECT
    GROUP_CONCAT(name)
    FROM tags as t1
    WHERE t1.uuid = tr.uuid and t1.type = "name"
    GROUP BY t1.uuid
) as names,
(
    SELECT GROUP_CONCAT(name)
    FROM tags as t2
    WHERE t2.uuid = tr.uuid and t2.type = "tag"
    GROUP BY t2.uuid
) as tags

FROM `tags` as tr

phpMyAdmin的转换:

CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` 
SQL SECURITY DEFINER 
VIEW `textagname` AS 
select 
`tr`.`uuid` AS `uuid`,
`tr`.`creator` AS `creator`,
(
    select group_concat(`t1`.`name` separator ',') AS `GROUP_CONCAT(name)` 
    from `tags` `t1` 
    where ((`t1`.`uuid` = `tr`.`uuid`) and (`t1`.`type` = 'name')) 
    group by `t1`.`uuid`
) AS `names`,
(
    select group_concat(`t2`.`name` separator ',') AS `GROUP_CONCAT(name)`
    from `tags` `t2` 
    where ((`t2`.`uuid` = `tr`.`uuid`) and (`t2`.`type` = 'tag')) 
    group by `t2`.`uuid`
) AS `tags` 
from `tags` `tr`

关于如何让我的观点更有效率的任何想法?

ps:这是tags表结构:

Column   Type         Null  Default  Comments
-------  -----------  ----  -------  ------------------
uuid     varchar(36)  No             key of texture
name     varchar(64)  No             tag name
creator  varchar(36)  Yes   NULL     creator of the tag
type     varchar(36)  No             name, or tag

1 个答案:

答案 0 :(得分:1)

无法真正解释为什么在phpMyAdmin转换为视图时查询速度变慢,但我会尝试以下查询:

SELECT
  uuid,
  creator,
  GROUP_CONCAT(CASE type WHEN 'name' THEN name END) AS names,
  GROUP_CONCAT(CASE type WHEN 'tag'  THEN name END) AS tags
FROM tags
WHERE type IN ('name', 'tag')
GROUP BY
  uuid,
  creator