MySql group by issue即使在group by中有聚合列

ruyhziif  于 2023-06-04  发布在  Mysql
关注(0)|答案(1)|浏览(385)

我正在努力使这个查询起作用

select bj.id,
       bj.m_id,       
       bj.b_s_id,
       bj.contact_phone,
       bj.f_a_date,
       bj.source_request_id,
       mw.w_id,
       COUNT(bjhs.id) as hs_count,
       CAST(IFNULL(SUM(bjhs.status), 0) as UNSIGNED) as hs_status
from b_j bj
inner join m_w mw on bj.m_id = mw.m_id
inner join b_j_h_s bjhs on bj.id = bjhs.b_j_id
inner join m_j mj on mj.m_id = bj.m_id
    and mj.j_id = 4
inner join m_w_j mwj on mwj.m_j_id = mj.id
    and mwj.m_w_id = mw.id
where bj.b_s_id = 2
    and (DATEDIFF(CURDATE(), (select min(bjhs.created_at)
        from b_j_h_s bjhs
        where bjhs.b_j_id = bj.id
        group by bjhs.b_j_id
        limit 1)) >= 35)
    and bj.deleted_at is null
having hs_count != hs_status
group by bj.id,
       bj.m_id,
       bj.contact_phone,
       bj.f_a_date,
       bj.source_request_id,
       mw.w_id

但我得到了语法错误。我的问题是,我必须group by(最后一个,不是子查询中的那个)聚合列,因为sql_mode=only_full_group_by,但是使用一些或所有列时,我得到了相同的错误。可能是什么问题,我如何解决它?
Here's a fiddle
PS.一个重要的注意事项是,我不能改变sql_mode=only_full_group_by和MySql版本是8.0.31

yquaqz18

yquaqz181#

我认为有几个问题:

  • having hs_count != hs_status应在group by之后定义
  • mw.w_id应为mw.m_id
  • bj。共享架构中不存在bariatric_status_id

Fiddle

相关问题