简体   繁体   English

如何获得不同的记录,但仅基于 MySQL 中的前 2 位数字

[英]How to get distinct records but on base on first 2 digits only in MySQL

I want to get distinct records (only one field) from a MySQL table, and that field contain only digits.我想从 MySQL 表中获取不同的记录(只有一个字段),并且该字段仅包含数字。

Example:例子:

00010000
01111100
01112000
01118000
02301201

But distinct records is considered on base on first 2 digits.但是根据前 2 位数字考虑不同的记录。 So in the case above, I need to get back only 3 records:所以在上面的例子中,我只需要取回 3 条记录:

00010000
01112000
02301201

More over, I would like to trim the rest of the digits, so the actual end result should be:此外,我想修剪 rest 的数字,所以实际的最终结果应该是:

00
01 
02

So distinct and group by will not cut here.如此独特和分组将不会在这里剪切。 Any idea?任何想法?

Assuming you wanted the least value from among duplicates, you could try:假设您希望重复项中的价值最小,您可以尝试:

SELECT t1.col
FROM yourTable t1
INNER JOIN
(
    SELECT LEFT(col, 2) AS prefix, MIN(col) AS min_col
    FROM yourTable
    GROUP BY LEFT(col, 2)
) t2
    ON LEFT(t1.col, 2) = t2.prefix AND
       t1.col = t2.min_col;

Note: Numbers in MySQL don't start with zeroes, so your requirement (and this answer) only make sense if your column is text.注意: MySQL 中的数字不以零开头,因此您的要求(以及此答案)仅在您的列是文本时才有意义。

DISTINCT will work fine with LEFT to give the results you want: DISTINCT可以与LEFT配合使用,以提供您想要的结果:

SELECT DISTINCT(LEFT(value, 2)) AS value
FROM data
ORDER BY value 

Output Output

00
01
02

Demo on dbfiddle dbfiddle 上的演示

If you only want the trimmed value, try this:如果您只想要修剪后的值,请尝试以下操作:

SELECT SUBSTRING(yourColumn,1,2) as trimmedval
FROM Table
GROUP BY SUBSTRING(yourColumn,1,2)

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

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