【问题标题】:Is there a way to rewrite this query to work as an SQL view有没有办法重写这个查询以作为 SQL 视图工作
【发布时间】:2012-04-29 15:27:25
【问题描述】:

我已经设法编写了以下查询,效果很好。我的问题是我多次使用它,我认为它需要自己的视图,但是当我让 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

【问题讨论】:

  • names 子查询应该做什么?您似乎没有使用它(除了将结果数相乘)。
  • 我试图对查询执行的操作是生成一个表,该表是每个纹理的 UUID,其中包含纹理名称及其标签的 CSV 列表。

标签: mysql sql phpmyadmin


【解决方案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

【讨论】:

  • 非常感谢@Andriy。更改我的搜索查询以使用基于此查询的新视图,并在不使用任何连接的情况下重写其余部分,每次搜索节省了近 6 秒!
猜你喜欢
  • 1970-01-01
  • 2020-10-24
  • 2022-01-05
  • 2018-08-01
  • 2020-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多