mysql - 如何在MySql中查找具有最高优先级的行?

标签 mysql sql

[抱歉,如果这是转发的话]

我有多种产品。它们可以属于多个组,即一种产品可以属于多个组。每个组都有一个优先级。我有 2 个表,一个具有 Product_id-group_id 映射,另一个具有 group_id-priority 映射。我需要一个product_id-group_id结果,它返回具有最高优先级的product_id的组。

例如 源表:

table1 = product_id | group_id      table2 = group_id | priority
         1          | g1                     g1       | 1   
         1          | g2                     g2       | 2
         2          | g1                     g3       | 3
         2          | g2
         2          | g3

期望的结果:

product_id | group
1          | g2        # because out of groups g1 and g2, g2 has more priority
2          | g3        # 3 = max_priority among groups g1, g2 and g3

我需要一个SQL 查询来返回此结果。如果你们能提出一个查询,使其仅返回所需的product_ids 列表的映射,那就更好了。

我们正在使用 MySQL 5.5。唯一的product_ids将<1m,组将不超过1000。

任何帮助或指示表示赞赏。谢谢大家。

最佳答案

您可以使用 substring_index()group_concat() 来完成此操作:

select t1.product_id,
       substring_index(group_concat(t1.group_id order by t2.priority desc), ',', 1) as group_id
from table1 t1 join
     table2 t2
     on t1.group_id = t2.group_id
group by t1.product_id;

关于mysql - 如何在MySql中查找具有最高优先级的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23664513/

相关文章:

sql - 用外键计算行数

sql - 如何将连接范围之外的数据捕获到 tempTBL 中

sql - 为包含列表的单元格返回多行

sql - 使用 RANGE 模式理解窗函数框架

mysql - 在 char 数据类型的字段中插入中文和日文字符

php - 合并两个日志类型特征查询的返回结果

mysql - 将 MySQL 数据保存在 Docker 容器中

mysql - 获取上一个工作日 + MySQL

mysql - 从 VB 程序向数据库添加数据 -> 安全方式?

PHP:将两个单独的 mysql 查询加入同一个 json 数据对象