MySQL查询有多个限制

时间:2016-02-25 17:45:00

标签: mysql many-to-many

我希望获得带有所有标签

的偏移O的N新闻
news
id | title

tag
id | name

news_tag
news_id | tag_id

如何在单个查询中执行此操作?

现在我首先得到N新闻。

  SELECT * FROM news LIMIT N, O

获取每条新闻的所有标签后:

SELECT n.id, nt.tag_id, t.name FROM news AS n 
JOIN news_tag AS nt ON n.id = nt.news_id
JOIN tag AS t ON nt.tag_id = c.id
WHERE n.id = curNewsId

是N + 1查询。我怎样才能做得更好?

1 个答案:

答案 0 :(得分:0)

尝试类似:

SELECT n.id, nt.tag_id, t.name 
FROM (SELECT id 
      FROM news 
      LIMIT N, O) AS n 
JOIN news_tag AS nt ON n.id = nt.news_id
JOIN tag AS t ON nt.tag_id = c.id

应该注意的是,LIMIT在没有ORDER BY子句的情况下应用会从news表中选择任意记录集。