【问题标题】:Can I limit by unique count of a specific column?我可以通过特定列的唯一计数来限制吗?
【发布时间】:2015-01-01 02:48:44
【问题描述】:

假设我有一个歌曲数据库。

ARTIST          |        SONG
-------------------------------------
Cloud Cult        The Meaning of 8
Cloud Cult        Pretty Voice
Jason Alexander   Today Was a Good Day
Jason Alexander   Like a Virgin
Jason Alexander   It Wasn't Me
Powderfinger      Like a Dog

我想要做的是发出一个查询,按 20 位艺术家的限制选择所有歌曲。不只是 20 条数据库记录,与这 20 位艺术家的歌曲一样多的记录。所以在上面的例子中,如果我限制为 2,我会得到 5 个结果,所有 Cloud Cult 的歌曲和 Jason Alexander 的所有歌曲。

这是 SQL 可以做到的吗?

【问题讨论】:

    标签: mysql sql database sqlite


    【解决方案1】:

    您需要创建一个艺术家子查询和LIMIT 所需艺术家数量的子查询:

    SQL Fiddle

    MySQL 5.5.32 架构设置

    CREATE TABLE Table1
        (`ARTIST` varchar(15), `SONG` varchar(20))
    ;
    
    INSERT INTO Table1
        (`ARTIST`, `SONG`)
    VALUES
        ('Cloud Cult', 'The Meaning of 8'),
        ('Cloud Cult', 'Pretty Voice'),
        ('Jason Alexander', 'Today Was a Good Day'),
        ('Jason Alexander', 'Like a Virgin'),
        ('Jason Alexander', 'It Wasn''t Me'),
        ('Powderfinger', 'Like a Dog')
    ;
    

    查询 1

    select t.* 
    from (select distinct ARTIST from table1 LIMIT 2) a 
    INNER JOIN table1 t on a.ARTIST = t.ARTIST
    

    Results

    |          ARTIST |                 SONG |
    |-----------------|----------------------|
    |      Cloud Cult |     The Meaning of 8 |
    |      Cloud Cult |         Pretty Voice |
    | Jason Alexander | Today Was a Good Day |
    | Jason Alexander |        Like a Virgin |
    | Jason Alexander |         It Wasn't Me |
    

    【讨论】:

      【解决方案2】:
      Select * FROM LibraryTable lt 
      WHERE lt.artist IN (SELECT 
                          DISTINCT lt2.artist 
                          FROM LibraryTable lt2 LIMIT ***X***)
      

      X 是您的艺术家限制。

      【讨论】:

        【解决方案3】:

        你可以使用group by function来选择具体的数据,这里是代码

        select table1.artist, table1.song from 
        (select artist from table1
          group by artist limit 2) t1 
        inner join table1 on t1.artist=table1.artist
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-02-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-05-01
          相关资源
          最近更新 更多