繁体   English   中英

SQL:foreach查询结果-运行查询

[英]SQL: foreach query result - run query

我有一个带有项目的 tableX,每个项目都有一个 category_id 和评级。 我想从每个类别中选取评分最高的项目。

我想我必须做类似的事情

SELECT DISTINCT category_id from tableX;

然后使用另一个查询运行 foreach 这些结果

SELECT * from tableX where category_id = ${1} ORDER BY rating, LIMIT 1;

或类似的东西

call foreach('SELECT distinct category_id FROM tableX', 'SELECT * from tableX WHERE category_id = ${1} ORDER BY rating DESC LIMIT 1')

编辑:

我添加了一些行示例

CREATE TABLE `tableX` (
  `id` bigint(20) UNSIGNED NOT NULL,
  `rating` double(6,1) DEFAULT '0.0',
  `category_id` int(10) UNSIGNED NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

为表tableX转储数据

INSERT INTO `tableX` (`id`, `rating`, `category_id`) VALUES
(1463, 8.0, 1),
(1464, 8.0, 1),
(1465, 8.0, 1),
(1466, 9.0, 1),
(1467, 9.0, 1),
(1468, 3.0, 1),
(1469, 8.0, 1),
(1470, 2.0, 1),
(1471, 4.0, 1),
(1472, 9.0, 1),
(1473, 5.0, 1),
(1474, 9.0, 1),
(1475, 10.0, 1),
(1476, 7.0, 1),
(1477, 7.0, 1),
(1478, 6.0, 1),
(1479, 10.0, 1),
(1480, 3.0, 1),
(1481, 7.0, 1),
(1482, 4.0, 1),
(1483, 7.0, 1),
(1484, 4.0, 1),
(1485, 2.0, 1),
(1486, 4.0, 1),
(1487, 5.0, 1),
(1488, 9.0, 1),
(1489, 8.0, 1),
(1490, 7.0, 1),
(1491, 10.0, 1),
(1492, 9.0, 1),
(1493, 9.0, 1),
(1494, 9.0, 2),
(1495, 3.0, 2),
(1496, 9.0, 2),
(1497, 9.0, 2),
(1498, 2.0, 2),
(1499, 4.0, 2),
(1500, 5.0, 2),
(1501, 7.0, 2),
(1502, 5.0, 2),
(1503, 7.0, 2),
(1504, 10.0, 2),
(1505, 6.0, 2),
(1506, 6.0, 4),
(1507, 1.0, 4),
(1508, 5.0, 4),
(1509, 7.0, 5),
(1510, 4.0, 5);

转储表的索引

ALTER TABLE `tableX`
  ADD PRIMARY KEY (`id`),
  ADD KEY `category_id` (`category_id`);

使用rank()row_number()

select x.*
from (select x.*,
             row_number() over (partition by category_id order by rating desc) as seqnum
      from tableX x
     ) x
where seqnum = 1;

对于平局,请使用rank() (即评分最高的所有行)。

以上适用于 MySQL 8+。 在早期版本中,您可以使用相关子查询。 就像是:

select x.*
from tableX x
where x.rating = (select max(x2.rating)
                  from tableX x2
                  where x2.category_id = x.category_id
                 );

如果您只需要使用第二种形式的一行,则:

select x.*
from tableX x
where x.id = (select x2.id
              from tableX x2
              where x2.category_id = x.category_id
              order by x2.rating desc
              limit 1
             );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM