简体   繁体   English

如何在mysql中为两列选择唯一值

[英]How to select only distinct values for two columns in mysql

I have created a table 我已经创建了一张桌子

CREATE TABLE `region_details` (
  `id` int(5) NOT NULL,
  `file_id` varchar(20) NOT NULL,
  `region` varchar(30) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

Lets assume I have 10 records as follows 假设我有10条记录,如下所示

id     file_id     region
1      aaa         a
2      bbb         b
3      ccc         a
4      ddd         c
5      abc         d
6      a01         a
7      j05         b
8      005         c
9      a1021       a
10     111j        b

I need id and region for distinct region values 我需要ID和区域以获取不同的区域值

   id     region
    1     a
    2     b
    4     c
    5     d

Simply do a GROUP BY , use MIN(id) to pick each region's first id. 只需执行GROUP BY ,使用MIN(id)选择每个区域的第一个ID。

select min(id) as id, region
from region_details
group by region

You can do it like this: 您可以这样做:

SELECT min(id),region
FROM YourTable
GROUP BY region

The other two answers are rolling up Id into an aggregate function ( min , or max or some other reduce-function), but looking at the data, it may turn out to be the case that what you want are all the unique combinations of id and region, which you can find by using the following: 其他两个答案将Id汇总为一个聚合函数( minmax或其他缩减函数),但查看数据,结果可能是您想要的都是id的唯一组合和区域,您可以使用以下方法找到:

select id, region
from yourtable
group by id, region

If you want to get an idea of how/whether/which columns are rolled up, due to the existence of multiple files for a given id/region combination, you might try: 如果您想了解如何/如何/哪些列进行汇总,由于给定ID /区域组合存在多个文件,您可以尝试:

select id, region, count(*)
from yourtable
group by id, region

Any rows with a count(*) value higher than 1 are indications that you've got multiple files scurried away under those particular combinations. 任何count(*)值大于1的行都表明您已经在这些特定组合下匆匆忙忙删除了多个文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM