我正在运行以下查询以从 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 3
到1,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/