mysql - 删除重复项 UNION ALL 检索到的帖子 sql, mysql

标签 mysql sql

我正在使用 UNION ALL 子句来检索用户的帖子。

SELECT * FROM $post WHERE condition 1

UNION ALL

SELECT * FROM $post WHERE condition 2

结果

Post 1
Post 2
Post 3
Post 3
Post 5

预期

Post 1
Post 2
Post 3 (display only once)
Post 5

问题

在使用 UNION ALL 时,如何只显示一次重复的帖子

最佳答案

使用UNION DISTINCT,或者只是UNION

https://dev.mysql.com/doc/refman/5.7/en/union.html说:

The default behavior for UNION is that duplicate rows are removed from the result. The optional DISTINCT keyword has no effect other than the default because it also specifies duplicate-row removal.

如果您的查询必须使用UNION ALL,则将其设为子查询并使用:

SELECT DISTINCT ... FROM ( ...subquery... ) AS t

关于mysql - 删除重复项 UNION ALL 检索到的帖子 sql, mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50827639/

相关文章:

php - SELECT FROM 以 JOIN 中的值命名的数据库

php - 如何在 Yii2 中连接到远程 mySQL 数据库

php - mysql 查询根据 3 个高级条件提取结果并在 php 中回显

MySQL 触发器 - 年月 (YYMM) 前缀 + 自动递增 ID

sql - 如何根据 Athena (Presto) 中的列值将一行分成多行?

c# - System.ArgumentNullException:值不能为null。 (参数 'connectionString')asp.net Core Docker-compose

sql - 如何在 Oracle SQL Developer 中查看 blob 数据

mysql - 使用 coalesce 和 join 计算一列与多行之间的差异

sql - 使用输出在合并语句中设置变量

sql - 在查询中使用 ROLLUP...小问题