Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 获取联接的前3项_Mysql_Join_Mariadb_Greatest N Per Group - Fatal编程技术网

Mysql 获取联接的前3项

Mysql 获取联接的前3项,mysql,join,mariadb,greatest-n-per-group,Mysql,Join,Mariadb,Greatest N Per Group,我有三张桌子: 产品、类别和产品类别每个类别中的产品 我想得到每一类中最贵的前三名产品 我有这个基本关系: select c.name , p.id , p.price from category c left join product_category pc on pc.category_id = category.id left join product p on pc.product_id = p.id 但现在我只想得到每个

我有三张桌子: 产品、类别和产品类别每个类别中的产品

我想得到每一类中最贵的前三名产品

我有这个基本关系:

select c.name
     , p.id
     , p.price 
  from category c
  left 
  join product_category pc
    on pc.category_id = category.id
  left 
  join product p 
    on pc.product_id = p.id
但现在我只想得到每个类别中最贵的3个

在这种情况下,我们可以使用任意数量的联接表,并且可以将其升级到任何更复杂的查询

没有循环,这可能吗


我将10.2.14-MariaDB-log与此模式一起使用

MySQL 8.0+&MariaDB 10.2+支持窗口函数,如dense_rank,它们适合处理您的案例。对于每个类别,我们根据产品价格分配排名,只抽取前三名的人。使用稠密_秩可以正确地处理关系,这意味着如果某个类别的产品具有相同的价格,则某个特定类别的输出中可以有3行以上。如果此行为不是首选行为,并且您希望在输出中看到最多3行,丢弃领带,请改用行数窗口函数

select name, id
from (
  select c.name, p.id, dense_rank() over (partition by c.id order by p.price desc) as rank
  from category c
  left join product_category pc on pc.category_id = c.id
  left join product p on pc.product_id = p.id
) t
where rank <= 3

在这种情况下,您的查询应该从类别表开始-你能在一个数据库中提供你的数据库模式吗?看看你使用的是哪个MySQL版本?