LIMIT不处理复杂查询

时间:2014-12-18 14:29:15

标签: mysql

我创建了一个生成复杂查询的函数,该查询为我的搜索引擎计算点数。它得到了正确的结果,但我无法限制输出行...这是为2字搜索生成的查询(“lorem ipsum”):

SELECT SQL_CALC_FOUND_ROWS
    `Search`.`model` AS `model`, 
    `Search`.`foreign_key` AS `id`, 
    SUM(`Search`.`points`) AS `points`
FROM (
    SELECT
        `i18n`.`foreign_key`, `i18n`.`model`,
        (CASE 
            WHEN `i18n`.`field` = "name" THEN 50
            WHEN `i18n`.`field` = "s_desc" THEN 20
        END) AS `points`
    FROM
        `i18n`
    WHERE
        `i18n`.`field` IN ("name", "s_desc") AND
        `i18n`.`locale` = "en-us" AND
        (`i18n`.`content` LIKE "lorem%" OR `i18n`.`content` LIKE "% lorem%")

    UNION ALL

    SELECT
        `tagged`.`foreign_key`, `tagged`.`model`, 
        "50" as `points`
    FROM
        `tagged`
    INNER JOIN
        `tags` ON
            `tags`.`id` = `tagged`.`tag_id` AND
            `tags`.`name` = "lorem"
    WHERE
        `tagged`.`language` = "en-us"
     UNION ALL 
    SELECT
        `i18n`.`foreign_key`, `i18n`.`model`,
        (CASE 
            WHEN `i18n`.`field` = "name" THEN 50
            WHEN `i18n`.`field` = "s_desc" THEN 20
        END) AS `points`
    FROM
        `i18n`
    WHERE
        `i18n`.`field` IN ("name", "s_desc") AND
        `i18n`.`locale` = "en-us" AND
        (`i18n`.`content` LIKE "ipsum%" OR `i18n`.`content` LIKE "% ipsum%")

    UNION ALL

    SELECT
        `tagged`.`foreign_key`, `tagged`.`model`, 
        "50" as `points`
    FROM
        `tagged`
    INNER JOIN
        `tags` ON
            `tags`.`id` = `tagged`.`tag_id` AND
            `tags`.`name` = "ipsum"
    WHERE
        `tagged`.`language` = "en-us"
    ) `Search`
GROUP BY
    `Search`.`model`,
    `Search`.`foreign_key`
ORDER BY
    `points` DESC;
LIMIT 5 OFFSET 0

请注意,我还尝试了LIMIT 5, 0,但仅LIMIT 5。它返回所有命中,而不仅仅是前5个。我做错了什么?

1 个答案:

答案 0 :(得分:0)

现在一切正常,;声明中的问题是ORDER

ORDER BY
    `points` DESC
LIMIT 5 OFFSET 0