简体   繁体   English

帖子和标签-加入限制

[英]Posts and tags - limit in join

I have 3 tables: posts , tags , *posts_tags* . 我有3个表: poststags ,* posts_tags *。 I want to list posts, and all tags associated with them, but to limit the results. 我想列出帖子以及与之关联的所有标签,但要限制结果。

This is what I do now: 这就是我现在要做的:

SELECT 
    p.*,
    t.*
FROM 
    (
        SELECT * FROM  posts LIMIT 0, 10
    ) as p
    LEFT JOIN
        posts_tags as pt
        ON pt.post_id = p.post_id
    LEFT JOIN
        tags as t
        ON t.tag_id = pt.tag_id

It is working fine, but it seems to be a little bit slow.. 它工作正常,但似乎有点慢。

Is there a better/faster way of doing this? 有更好/更快的方法吗? Can I apply LIMIT somewhere else for better results? 我可以在其他地方应用LIMIT以获得更好的结果吗?

EDIT: I want to limit posts, and not results. 编辑:我想限制职位,而不是结果。 A post can have many tags. 帖子可以有很多标签。

SELECT 
    p.*,
    t.*
FROM 
    posts as p
    LEFT JOIN
        posts_tags as pt
        ON pt.post_id = p.post_id
    LEFT JOIN
        tags as t
        ON t.tag_id = pt.tag_id
LIMIT 0, 10

Should work ;) 应该管用 ;)

EDIT 编辑

MySQL is quite slow when running multiple joins, in my opinion it's better to separate your query into two and then join the result in your app code (application overhead should not be so big since its only 10 results). 当运行多个联接时,MySQL的运行速度非常慢,我认为最好将查询分为两个,然后将结果联接到应用程序代码中(应用程序开销不应该太大,因为它只有10个结果)。

Try running your query with the EXPLAIN keyword in front of it: 尝试使用查询前面的EXPLAIN关键字运行查询:

EXPLAIN SELECT ...

This will give you and idea about how MySQL is executing your query. 这将为您提供有关MySQL如何执行查询的想法。 Maybe you miss a key or an index somewhere. 也许您错过某个地方的键或索引。 Here's how to read the result of EXPLAIN: http://dev.mysql.com/doc/refman/5.5/en/explain-output.html 这是读取EXPLAIN结果的方法: http : //dev.mysql.com/doc/refman/5.5/en/explain-output.html

Have you tried moving the limiting subquery to the where clause instead: 您是否尝试过将限制子查询移至where子句:

SELECT 
    p.*,
    t.*
FROM 
    posts as p
LEFT JOIN
    posts_tags as pt
    ON pt.post_id = p.post_id
LEFT JOIN
    tags as t
    ON t.tag_id = pt.tag_id
WHERE
    p.post_id in (select post_id from post limit 0,10)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM