gpt4 book ai didi

mysql - 使用嵌套表和分组按最低等级获取记录 - MYSQL

转载 作者:行者123 更新时间:2023-11-29 18:01:27 25 4
gpt4 key购买 nike

我有一个查询问题,之前用 2 个表和不同的数据库结构解决了,现在我有 3 个表,但无法得到正确的结果

leads table - regular leads table with id, firstname, etc...

statuses table - id, lead_id, brand_id, map_id
lead_id is relationship key for id in lead
map_id is relationship key for map_keys table

map_keys table - id, name, rank

规则:每个潜在客户可以有多个状态,也可以没有状态

即使同一潜在客户有两个或多个状态,查询也应仅打印最低状态

示例:

lead: id = 3, 
statuses: id = 7, lead_id = 3, map_id = 5
and another record:
statuses: id = 10, lead_id = 3, map_id = 1

map_keys:
id = 5, rank = 5
id = 1, rank = 1

in the result I should get
lead_id = 3, map_id = 1

过去我在状态表中有排名,所以我的解决方案是

SELECT  IF(s2.rank IS NULL, s.rank, s2.rank) AS rank  FROM `leads` l 
LEFT JOIN statuses s ON s.lead_id = l.id
LEFT JOIN statuses s2 ON s2.lead_id = s.lead_id AND s.rank > s2.rank
GROUP BY l.id

但是使用新的数据库结构我无法得到正确的结果,我希望我的问题是可以理解的,如果不是我会尽力更好地解释它,谢谢!

最佳答案

我解决了我的问题,我的最终查询是

SELECT * FROM leads                                                                                                 
LEFT JOIN (
SELECT lead_id, mk.name, mk.rank FROM `statuses` s
JOIN map_keys mk ON mk.id = s.map_id
JOIN statuses_maps sm ON sm.id = s.status_id
ORDER BY rank ASC ) as s ON lead_id = lead.id
GROUP BY leads.id

关于mysql - 使用嵌套表和分组按最低等级获取记录 - MYSQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48286976/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com