簡體   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