【问题标题】:Selecting rows on Unique Pairs of columns from mysql Table从 mysql 表中选择唯一对列上的行
【发布时间】:2014-09-29 10:49:18
【问题描述】:

我有一张桌子table。

现在这有三列 table_id,content_id,content_type

我想要的是根据唯一的列对来选择行。

说例如我有这样的行-->

id|content_id|content_type|

1   1          shirt
2   1          trouser
3   4          skirt
4   4          shirt
5   3          trouser
6   5          jeans
7   1          trouser
8   5          jeans

我想要一个选择 id->1,2,3,4,5,6 行的查询。

id->7,8的行不被选中

因此得出结论,我不想要选择 complete Duplicates of Rows

【问题讨论】:

    标签: php mysql sql select distinct


    【解决方案1】:

    您可以使用自联接来选择每个组的最小行数

    select t.* from 
    test t
    join (
          select min(id) id ,content_id,content_type
          from test
          group by content_id,content_type
       ) t1
    on(t.id = t1.id 
       and t.content_id = t1.content_id 
       and t.content_type = t1.content_type)
    

    Demo

    或者如果您的表格中只有这 3 列,那么您可以简单地使用 min()

    select min(id) id ,content_id,content_type
    from test
    group by content_id,content_type
    

    Demo

    【讨论】:

      【解决方案2】:

      这是 mysql 特有的:如果您使用 GROUP BY 函数而不使用聚合函数,则 group by 子句将表现为不同的,并选择第一个不同的行。

      select id, content_id, content_type from test group by content_id, content_type order by id
      

      Demo

      【讨论】:

      • 您可以使用@Khalid 的解决方案,并将其更改为使用 max() 而不是 min()。
      猜你喜欢
      • 1970-01-01
      • 2017-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多