Moh*_*eri 53 sql select distinct duplicates
我有一个包含3列的表,如下所示:
+------------+---------------+-------+
| Country_id | country_title | State |
+------------+---------------+-------+
Run Code Online (Sandbox Code Playgroud)
此表中有许多记录.他们中的一些state
人和其他人没有.现在,想象一下这些记录:
1 | Canada | Alberta
2 | Canada | British Columbia
3 | Canada | Manitoba
4 | China |
Run Code Online (Sandbox Code Playgroud)
我需要没有任何重复的国名.其实我需要他们id
和title
,什么是最好的SQL命令,使这个?我DISTINCT
在下面的表格中使用但是我无法获得适当的结果.
SELECT DISTINCT title,id FROM tbl_countries ORDER BY title
Run Code Online (Sandbox Code Playgroud)
我想要的结果是这样的:
1, Canada
4, China
Run Code Online (Sandbox Code Playgroud)
Mar*_*ers 93
试试这个:
SELECT MIN(id) AS id, title
FROM tbl_countries
GROUP BY title
Run Code Online (Sandbox Code Playgroud)
小智 31
DISTINCT
是关键字
对我来说你的查询是正确的
试着先尝试这样做
SELECT DISTINCT title,id FROM tbl_countries
Run Code Online (Sandbox Code Playgroud)
稍后您可以尝试订购.
shA*_*A.t 11
对于使用DISTINCT
关键字,您可以像这样使用它:
SELECT DISTINCT
(SELECT min(ti.Country_id)
FROM tbl_countries ti
WHERE t.country_title = ti.country_title) As Country_id
, country_title
FROM
tbl_countries t
Run Code Online (Sandbox Code Playgroud)
对于使用ROW_NUMBER()
,您可以像这样使用它:
SELECT
Country_id, country_title
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY country_title ORDER BY Country_id) As rn
FROM tbl_countries) t
WHERE rn = 1
Run Code Online (Sandbox Code Playgroud)
使用时LEFT JOIN
,您可以使用:
SELECT t1.Country_id, t1.country_title
FROM tbl_countries t1
LEFT OUTER JOIN
tbl_countries t2 ON t1.country_title = t2.country_title AND t1.Country_id > t2.Country_id
WHERE
t2.country_title IS NULL
Run Code Online (Sandbox Code Playgroud)
使用EXISTS
,您可以尝试:
SELECT t1.Country_id, t1.country_title
FROM tbl_countries t1
WHERE
NOT EXISTS (SELECT *
FROM tbl_countries t2
WHERE t1.country_title = t2.country_title AND t1.Country_id > t2.Country_id)
Run Code Online (Sandbox Code Playgroud)