我有一个varchar列的表,我想找到在这个列中有重复值的所有记录。我可以使用什么查询来查找重复项?
当前回答
一个非常晚的贡献…万一这能帮助到以后的任何人…我有一个任务是在一个银行应用程序中找到匹配的交易对(实际上是账户到账户转账的双方),以识别每个账户间转账交易的“从”和“到”,所以我们最终得到了这个:
SELECT
LEAST(primaryid, secondaryid) AS transactionid1,
GREATEST(primaryid, secondaryid) AS transactionid2
FROM (
SELECT table1.transactionid AS primaryid,
table2.transactionid AS secondaryid
FROM financial_transactions table1
INNER JOIN financial_transactions table2
ON table1.accountid = table2.accountid
AND table1.transactionid <> table2.transactionid
AND table1.transactiondate = table2.transactiondate
AND table1.sourceref = table2.destinationref
AND table1.amount = (0 - table2.amount)
) AS DuplicateResultsTable
GROUP BY transactionid1
ORDER BY transactionid1;
The result is that the DuplicateResultsTable provides rows containing matching (i.e. duplicate) transactions, but it also provides the same transaction id's in reverse the second time it matches the same pair, so the outer SELECT is there to group by the first transaction ID, which is done by using LEAST and GREATEST to make sure the two transactionid's are always in the same order in the results, which makes it safe to GROUP by the first one, thus eliminating all the duplicate matches. Ran through nearly a million records and identified 12,000+ matches in just under 2 seconds. Of course the transactionid is the primary index, which really helped.
其他回答
对GROUP BY子句执行SELECT操作。假设name是你想要在其中找到重复项的列:
SELECT name, COUNT(*) c FROM table GROUP BY name HAVING c > 1;
这将返回一个在第一列中包含名称值的结果,以及该值在第二列中出现次数的计数。
SELECT varchar_col
FROM table
GROUP BY varchar_col
HAVING COUNT(*) > 1;
SELECT
t.*,
(SELECT COUNT(*) FROM city AS tt WHERE tt.name=t.name) AS count
FROM `city` AS t
WHERE
(SELECT count(*) FROM city AS tt WHERE tt.name=t.name) > 1 ORDER BY count DESC
如果你想删除重复使用DISTINCT
否则使用这个查询:
SELECT users.*,COUNT(user_ID) as user FROM users GROUP BY user_name有用户>
进一步采取@maxyfc的答案,我需要找到所有返回的重复值的行,这样我就可以在MySQL Workbench中编辑它们:
SELECT * FROM table
WHERE field IN (
SELECT field FROM table GROUP BY field HAVING count(*) > 1
) ORDER BY field
推荐文章
- 我如何得到“id”后插入到MySQL数据库与Python?
- MySQL工作台:如何保持连接活动
- 'create_date'时间戳字段的默认值无效
- 我可以从一个完整的mysql mysqldump文件恢复一个表吗?
- 计数在VARCHAR字段中字符串的出现次数?
- 修改一个MySQL列为AUTO_INCREMENT
- 在ROR迁移期间,将列类型从Date更改为DateTime
- 如何删除所有MySQL表从命令行没有DROP数据库权限?
- 从主机连接到docker容器中的mysql
- 如果任何字段包含NULL, MySQL CONCAT将返回NULL
- MySQL中的字符串连接
- Laravel未知列'updated_at'
- MySQL更新内部连接表查询
- 根据查询结果设置用户变量
- 不能删除外键约束中需要的索引