php - mysql inner join语句和内存过度使用!

标签 php mysql concatenation inner-join

我正在运行以下查询以从 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 = '' OR

ns.associated = '' OR

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

是否有任何其他方式来编写波纹管语句以包括所有故事,即使是那些没有标签的故事!?

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

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

最佳答案

您的条件 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

关于php - mysql inner join语句和内存过度使用!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3533866/

相关文章:

php - PHP 帮助下的动态复选框

php - 对 php 文件的 Ajax 调用不适用于该文件中的 'require_once'

PHP:INPUT_POST(在 filter_input_array 中使用)覆盖之前对 $_POST 的所有修改

php - mysql查询自增

mysql - 使用 mySQL 将时间舍入到最接近的 6 分钟

java - 如何将一组数字连接成一个数字

php - 用于匹配传递的函数/方法参数的正则表达式

mysql - 以mysql日期格式存储时区

mysql - 在 SELECT 语句中设置变量 - MySQL

python - 水平连接两个 CSV 文件