select a.* ,b.flow_id from daiban_order_serve as a left join daiban_order_serve_flow as b on b.daiban_serve_id = a.id where 1 and supplier_id = 23 and b.uid = 100031 and b.is_kais = 2 and b.is_accept = 1 order by create_time desc limit 0,20 帮我优化一下这个mysql语句去除重复daiban_serve_id值的,但是要优先显示is_kais不等于2的
时间: 2023-05-21 20:04:30 浏览: 164
毕节热线OA办公系统
好的,这个 mysql 语句可以这样优化:
SELECT DISTINCT a.*, b.flow_id
FROM daiban_order_serve AS a
LEFT JOIN (
SELECT daiban_serve_id, MAX(flow_id) flow_id
FROM daiban_order_serve_flow
WHERE uid = 100031 AND is_accept = 1
GROUP BY daiban_serve_id
) AS b
ON b.daiban_serve_id = a.id
WHERE supplier_id = 23 AND IFNULL(b.is_kais != 2, true)
ORDER BY create_time DESC
LIMIT 0, 20;
这个语句会对 daiban_order_serve 和 daiban_order_serve_flow 两张表进行左联接,然后使用子查询获取每个 daiban_serve_id 对应的最大流程 ID 和去重后的结果集。
注意我用了 IFNULL(b.is_kais != 2, true) 来判断 is_kais 不等于 2,这样既可以显示 is_kais 不等于 2 的记录,也可以显示没有记录的 daiban_order_serve。
阅读全文