php - 我如何以提供相同输出的方式重写它

标签 php mysql laravel

我有一个像这样的 mysql 查询:

SELECT 
    bp.id, 
    COUNT(*) AS total
FROM
    blog_posts bp
JOIN
    tagged tg ON
        tg.taggable_id = bp.id
        AND tg.taggable_type = 'App\Storage\BlogPost'
JOIN
    tags t ON
        t.id = tg.tag_id
WHERE
    bp.user_id = 1
GROUP BY
    t.id
ORDER BY
    total DESC,
    t.count DESC
LIMIT
    3

我得到一个错误:

Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'example.bp.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

我如何以提供相同输出的方式重写它?

我在 MySQL 5.7.17 和 Homestead Laravel 中工作

最佳答案

每当您执行 GROUP BY 时,您添加到 SELECTORDER BY 子句中的所有内容都需要在 中GROUP BY 子句,除非您使用聚合函数,例如 MIN()、MAX()、SUM()、AVG() 等。

在这种情况下,您的 order by 子句中有 t.count DESC,像这样编写查询将为您提供所需的结果。

SELECT
    id,
    total
FROM
    (
        SELECT 
            bp.id, 
            COUNT(*) AS total,
            MAX(t.count) count
        FROM
            blog_posts bp
        JOIN
            tagged tg ON
                tg.taggable_id = bp.id
                AND tg.taggable_type = 'App\Storage\BlogPost'
        JOIN
            tags t ON
                t.id = tg.tag_id
        WHERE
            bp.user_id = 1
        GROUP BY
            bp.id,
            t.id
        LIMIT
            3
    ) a
ORDER BY
    total DESC,
    `count` DESC

如果你不关心最终结果中是否包含计数,那么你可以这样做

SELECT 
    bp.id, 
    COUNT(*) AS total,
    MAX(t.count) count
FROM
    blog_posts bp
JOIN
    tagged tg ON
        tg.taggable_id = bp.id
        AND tg.taggable_type = 'App\Storage\BlogPost'
JOIN
    tags t ON
        t.id = tg.tag_id
WHERE
    bp.user_id = 1
GROUP BY
    bp.id,
    t.id
ORDER BY
    total DESC,
    t.count DESC
LIMIT
    3

关于php - 我如何以提供相同输出的方式重写它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42838490/

相关文章:

php - 如何在 Laravel 中获取双请求名称到数组?

mysql - 创建 TreeView 循环查询

c# - C# mysql 命令执行过程中遇到 fatal error

mysql - SQL - 检索前天的记录

php - 按聚合函数排序 Laravel Eloquent

php - 图片上传/Laravel 将图片存储为 .tmp 而不是 .img 文件

PHP - 检测传入的 url 从另一个源/url 请求 php 页面

php - 如果 use_controller 设置为 true,则 Assetic 不起作用

javascript - Iron-ajax 响应为 php json 响应返回 null

php - Laravel 5 : Handle exceptions when request wants JSON