0

我有一个名为数据的表:

create table data
(
   ID int primary key,
   val varchar(50),
   forID int

   constraint fk_forID foreign key (forID) references otherTable(forID)
)

我有一个名为 dataFrequencies 的视图

create view dataFrequencies (val, freq)
as select val, COUNT(*)
     from data
 group by val
 order by freq desc

我想要的是表中前五十行中的行子集datavaldataFrequencies

我目前的解决方案有点迂回。我创建了一个包含前 50 行 dataFrequencies 的表 topFifty。然后我创建一个视图 topFiftyVals,它从数据中选择所有数据,但在表 topFifty 上进行内部连接:

create table topFifty
(
   val varchar(50) primary key
)

insert into topFifty select val from dataFrequencies order by frequency desc limit 50;

create view topFiftyVals (ID, val, forID)
as select *
     from data d
inner join topFifty tf on d.val = tf.val

我确信有某种直接查询方法可以做到这一点!感谢所有的帮助!

4

2 回答 2

1

你不能这样做:

SELECT *
  FROM data
 WHERE val IN (SELECT val 
                 FROM dataFrequencies 
               ORDER BY frequency DESC 
               LIMIT 50);
于 2012-12-02T00:14:05.037 回答
1

是的,有一个直接的方法。这是您topFiftyVals认为的代码,略有改动:

     select d.*, tf.freq
       from data d
 inner join ( select val, COUNT(*) AS freq
                from data
            group by val
            order by freq desc
               limit 50
            ) tf 
         on d.val = tf.val ;
于 2012-12-02T00:14:26.030 回答