4

我的数据库中有一个表,我在其中存储新闻文章的类别,每次用户阅读一篇文章时,它都会增加相关列中的值。像这样:

在此处输入图像描述

现在我想执行一个查询,我可以在其中获取每条记录的 4 个最高值的列名。例如,对于用户 9,它将返回:

在此处输入图像描述

我尝试了几件事,搜索了很多,但不知道该怎么做。谁能帮我?

4

4 回答 4

4

这应该这样做:

select
  userid,
  max(case when rank=1 then name end) as `highest value`,
  max(case when rank=2 then name end) as `2nd highest value`,
  max(case when rank=3 then name end) as `3rd highest value`,
  max(case when rank=4 then name end) as `4th highest value`
from
(
  select userID, @rownum := @rownum + 1 AS rank, name, amt from (
    select userID, Buitenland as amt, 'Buitenland' as name from newsarticles where userID = 9 union
    select userID, Economie, 'Economie' from newsarticles where userID = 9 union
    select userID, Sport, 'Sport' from newsarticles where userID = 9 union
    select userID, Cultuur, 'Cultuur' from newsarticles where userID = 9 union
    select userID, Wetenschap, 'Wetenschap' from newsarticles where userID = 9 union
    select userID, Media, 'Media' from newsarticles where userID = 9
  ) amounts, (SELECT @rownum := 0) r
  order by amt desc
  limit 4
) top4
group by userid

演示:http ://www.sqlfiddle.com/#!2/ff624/11

于 2012-05-24T18:34:12.530 回答
1

一个非常简单的方法如下所示

select userId, substring_index(four_highest,',',1) as 'highest value', substring_index(substring_index(four_highest,',',2),',',-1) as '2th highest value',  substring_index(substring_index(four_highest,',',3),',',-1) as '3 rd highest value',  substring_index(four_highest,',',-1) as '4th highest value'   from
(
select userid, convert(group_concat(val) using utf8) as four_highest from
(
select userId,Buitenland as val,'Buitenland' as col from test where userid=9 union
select userId,Economie as val,' Economie' as col from test where   userid=9 union
select userId,Sport as val ,'Sport' as col from test where  userid=9 union
select userId,Cultuur as val,'Cultuur' as col from test where userid=9 union
select userId,Wetenschap as val,'Wetenschap' as col from test where userid=9 union
select userId,Media as val,'Media' as col from test where  userid=9 order by val desc limit 4
) inner_query
)outer_query;
于 2012-05-25T04:03:52.287 回答
0

PL/SQL,也许吧?设置 user_id,查询您的表,将返回的行存储在 nx2 列名和值数组中(其中 n 是列数)并根据值对数组进行排序。

当然,正确的做法是以@octern 建议的方式重新设计您的数据库。

于 2012-05-24T18:43:25.897 回答
0

这将使您开始了解从单行上的多个列中获取最高值的概念(针对您的特定表进行修改 - 我创建了一个假表)。

create table fake 
(
  id int Primary Key,
  col1 int,
  col2 int,
  col3 int,
  col4 int 
)
insert into fake values (1, 5, 9, 27, 10)
insert into fake values (2, 3, 5, 1, 20)
insert into fake values (3, 89, 9, 27, 6)
insert into fake values (4, 17, 40, 1, 20)

SELECT *,(SELECT Max(v) 
FROM (VALUES (col1), (col2), (col3), (col4) ) AS value(v))
FROM fake
于 2012-05-24T19:52:13.447 回答