mysql 条件顺序,按顺序选择Mysql条件组的问题

本文讨论了如何通过SQL查询获取服务列表,按照KPI的指定顺序排序。问题在于原始查询未能按预期结果呈现,通过分析发现sql_mode设置问题。提供了几种解决方案,包括使用GROUP BY和DISTINCT,以及根据服务ID和最早的KPI顺序排序。
摘要由CSDN通过智能技术生成

Each service has different KPIs. These KPIs are ordered with the field order in the table checklist_has_kpi.

I want a list of separate services ordered by the order assigned to the KPI.

I have this query:

SELECT s.serviceid, s.servicenameit, s.servicenameen

FROM services s, kpi k, checklist_has_kpi chk

WHERE s.serviceid=k.serviceid AND k.kpiid=chk.kpiid AND k.inreport='yes' AND chk.checklistid=61

GROUP BY s.serviceid ORDER BY chk.order ASC

But it does not produce the result that I expect and I do not understand what's wrong in the query written by me.

Give me a hand?

If something is unclear just ask!

thanks

解决方案

If you add

SET SESSION sql_mode = 'ONLY_FULL_GROUP_BY';

Then you'll see the why other RDBMS won't allow this syntax:

3 un-aggregated columns in SELECT but one in GROUP BY

ORDER BY column is not in GROUP BY/SELECT and not aggregated

If you want to GROUP BY rather then DISTINCT, then you need to GROUP BY all column in the SELECT

SELECT s.serviceid, s.servicenameit, s.servicenameen

FROM services s, kpi k, checklist_has_kpi chk

WHERE s.serviceid=k.serviceid AND k.kpiid=chk.kpiid AND k.inreport='yes' AND chk.checklistid=61

GROUP BY s.serviceid, s.servicenameit, s.servicenameen

But then you have no chk.order to order by, whether using GROUP BY or DISTINCT

So what about this, ignoring duplicates completely?

SELECT s.serviceid, s.servicenameit, s.servicenameen

FROM services s, kpi k, checklist_has_kpi chk

WHERE s.serviceid=k.serviceid AND k.kpiid=chk.kpiid AND k.inreport='yes' AND chk.checklistid=61

ORDER BY chk.order ASC

Or this to ORDER BY the earliest order per 3x services columns

SELECT s.serviceid, s.servicenameit, s.servicenameen

FROM services s, kpi k, checklist_has_kpi chk

WHERE s.serviceid=k.serviceid AND k.kpiid=chk.kpiid AND k.inreport='yes' AND chk.checklistid=61

GROUP BY s.serviceid, s.servicenameit, s.servicenameen

ORDER BY MIN(chk.order)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值