【问题标题】:MySQL Select limit for paginationMySQL选择分页限制
【发布时间】:2012-04-17 11:56:04
【问题描述】:

我有一个从我的表中选择的结果:

id  tag
1   hey
1   wow
2   cry
87   game
87   bmw
6   lady
7   wow

但是我通过 JOIN 得到了这个结果。 我的完整 SQL 查询:

SELECT sites.id, sites.host, sites.url, sites.password, sites.status, sites.pr, sites.tyc, sites.alexa, sites.lastcheck, sites.comment, tags.tagname, tags.tagid FROM sites
LEFT JOIN sites_tags ON sites_tags.shellid = sites.id 
LEFT JOIN tags ON sites_tags.tagid = tags.tagid

对于分页,我需要 3 个来自查询的实际数据。

如果我的查询 - LIMIT 3,我想得到 ​​p>

1   hey
1   wow
2   cry
87   game
87   bmw

但不是

 1   hey
 1   wow
 2   cry

例如我需要所有受 ID 限制的结果,而不是行。

抱歉英语不好。

【问题讨论】:

  • 您提供的查询不会产生您正在显示的示例数据集。让人很难理解你到底想达到什么目标。
  • 不知道这是否是最好的解决方案,但我曾经为具有多个连接的查询创建视图。限制没有问题,当我需要直接在数据库中检查某些内容时,我也可以在特殊情况下轻松使用它

标签: mysql select join pagination unique


【解决方案1】:
SELECT 
    s.id, 
    s.host, 
    s.url, 
    s.password, 
    s.status, 
    s.pr, 
    s.tyc, 
    s.alexa, 
    s.lastcheck, 
    s.comment, 
    tags.tagname, 
    tags.tagid 
FROM (
    SELECT
        id, 
        host, 
        url, 
        password, 
        status, 
        pr, 
        tyc, 
        alexa, 
        lastcheck, 
        comment
    FROM sites
    LIMIT 3
) s
LEFT JOIN sites_tags ON sites_tags.shellid = s.id 
LEFT JOIN tags ON sites_tags.tagid = tags.tagid

这假设您想要的是与恰好 3 个站点相关的标签。这将选择 3 个站点的站点信息,然后还将选择任何标记(如果有)。

但是它不会精确地返回你想要的,你最好做一个查询来选择sites中的所有字段

SELECT
    id, 
    host, 
    url, 
    password, 
    status, 
    pr, 
    tyc, 
    alexa, 
    lastcheck, 
    comment
FROM sites
LIMIT 3

然后再进行以下操作以获取这些网站的标签。

SELECT 
    sites_tags.shellid AS id, 
    tags.tagname, 
    tags.tagid 
FROM sites_tags
INNER JOIN tags ON sites_tags.tagid = tags.tagid
WHERE sites_tags.shellid IN (..... your ids go here ......)

【讨论】:

    【解决方案2】:

    (猜测id指的是sites.id

    FROM sites 替换为:

    FROM ( SELECT * 
           FROM sites 
           ORDER BY whatever 
           LIMIT 3
         ) AS sites
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多