SELECT DISTINCT field1, field2, field3, ......
FROM table;
我试图完成以下SQL语句,但我希望它返回所有列。 这可能吗?
就像这样:
SELECT DISTINCT field1, *
FROM table;
SELECT DISTINCT field1, field2, field3, ......
FROM table;
我试图完成以下SQL语句,但我希望它返回所有列。 这可能吗?
就像这样:
SELECT DISTINCT field1, *
FROM table;
当前回答
这是一个简单的解决方法:
WITH cte AS /* Declaring a new table named 'cte' to be a clone of your table */
(SELECT *, ROW_NUMBER() OVER (PARTITION BY id ORDER BY val1 DESC) AS rn
FROM MyTable /* Selecting only unique values based on the "id" field */
)
SELECT * /* Here you can specify several columns to retrieve */
FROM cte
WHERE rn = 1
其他回答
Try
SELECT table.* FROM table
WHERE otherField = 'otherValue'
GROUP BY table.fieldWantedToBeDistinct
limit x
好问题@aryaxt——你可以看出这是一个好问题,因为你5年前问过这个问题,而我今天在试图找到答案时偶然发现了它!
我只是试图编辑接受的答案,以包括这一点,但如果我的编辑没有使它:
如果你的表不是那么大,并且假设你的主键是一个自动递增的整数,你可以这样做:
SELECT
table.*
FROM table
--be able to take out dupes later
LEFT JOIN (
SELECT field, MAX(id) as id
FROM table
GROUP BY field
) as noDupes on noDupes.id = table.id
WHERE
//this will result in only the last instance being seen
noDupes.id is not NULL
SELECT * from table where field in (SELECT distinct field from table)
SELECT *
FROM tblname
GROUP BY duplicate_values
ORDER BY ex.VISITED_ON DESC
LIMIT 0 , 30
在ORDER BY我刚刚把例子放在这里,你也可以在这里添加ID字段
我建议使用
SELECT * from table where field1 in
(
select distinct field1 from table
)
这样,如果field1在多个行中有相同的值,将返回所有记录。