mysql内连接语句和内存过度使用!

时间:2010-08-20 18:42:59

标签: php mysql concatenation inner-join

即时运行bellow查询从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,'%' ))

问题在内部加入状态中,如果我删除

  

ns.tags =''OR

  

ns.associated =''OR

内存过度使用问题将得到解决,但无法显示空标记字段的故事

有没有其他方法可以写下bellow语句来包含所有故事甚至那些没有标签的故事!?

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

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

1 个答案:

答案 0 :(得分: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 31,2,3的数据格式的情况下,您至少可以通过使用来删除Concat()LIKE稍快FIND_IN_SET(str, strlist)


为了完整起见,万一你改变主意:http://en.wikipedia.org/wiki/Database_normalization