【问题标题】:mysql inner join statement and memory overuse !mysql内部连接语句和内存过度使用!
【发布时间】:2011-04-01 19:45:24
【问题描述】:

我正在运行波纹管查询以从 3 个 mysql 表中获取,它工作正常,但它增加了内存使用量,有时需要 10 秒才能开始加载页面

  INNER JOIN table_tags AS ntg ON (ns.tags = '' OR CONCAT(' ',COALESCE(ns.tags,' '),' ') LIKE CONCAT('% ',ntg.tid,' %'))
  INNER JOIN table_topics AS nto ON (ns.associated = '' OR CONCAT(' ',COALESCE(ns.associated,'-'),' ') LIKE CONCAT('%',nto.topicid,'%' ))

问题在 Inner Join statemnet 中,如果我删除了

ns.tags = '' 或

ns.associated = '' 或

内存过度使用问题将得到修复,但无法显示带有空标签字段的故事

有没有其他方法可以写出下面的声明来包括所有故事,即使是那些没有标签的故事!?

  INNER JOIN table_tags AS ntg ON (ns.tags = '' OR CONCAT(' ',COALESCE(ns.tags,' '),' ') LIKE CONCAT('% ',ntg.tid,' %'))

我的标签 id 存储在 table_ns 中,例如 (14 17 2),用空格分隔

【问题讨论】:

    标签: php mysql concatenation inner-join


    【解决方案1】:

    您的条件ns.tags = '' OR ... 意味着如果ns.tags = '' 为真,则table_stories 中的这条记录将与table_tags 中的所有记录连接。与ns.associated = '' OR .. 相同。这可以轻松“创建”huuuge 结果集,而这很可能不是您想要的。
    如果您真的不想/不能更改/规范化表结构(正如您在我之前回答的评论中所述),我最好的猜测是使用两个 LEFT JOINs 之类的:

    SELECT
      ns.*,
      ntg.tid,
      nto.topicid,
      group_concat(DISTINCT ntg.tag ) as mytags,
      group_concat(DISTINCT ntg.slug ) as tagslug,
      group_concat(DISTINCT nto.topicname ) as mytopics,
      group_concat(DISTINCT nto.slug ) as topicslug,
      ns.counter AS counter_num
    FROM
      table_stories AS ns
    LEFT JOIN
      table_tags AS ntg
    ON
      CONCAT(' ', ns.tags,' ') LIKE CONCAT('% ',ntg.tid,' %')
    LEFT JOIN
      table_topics AS nto
    ON
      CONCAT(' ', ns.associated, ' ') LIKE CONCAT('%',nto.topicid,'%' )
    WHERE
      time <= '4711'
    GROUP BY
      ns.sid
    ORDER BY
      ns.sid DESC,ns.hotnews DESC
    

    但是 MySQL 不能为此使用索引,因此查询将导致全表扫描。它还需要临时表和文件排序,即查询相对较慢。
    无需更改表结构,但将数据格式从1 2 3 更改为1,2,3,您至少可以通过使用稍快的FIND_IN_SET(str, strlist) 摆脱Concat()LIKE


    仅出于完整性考虑,以防您改变主意:http://en.wikipedia.org/wiki/Database_normalization

    【讨论】:

      猜你喜欢
      • 2011-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-13
      • 1970-01-01
      • 2017-08-30
      • 1970-01-01
      相关资源
      最近更新 更多