php - 如何从表中删除重复/对应的值?

标签 php mysql sql

我有一个与此类似的表结构:

send_id | rec_id

它填充了以下示例数据:

id1 | id2

id2 | id1

id3 | id1

id3 | id2

id4 | id1

id1 | id4

我尝试在 id1 上使用此查询:

SELECT * from inbox WHERE (send_id="id1" OR rec_id="id1") GROUP BY send_id,rec_id

但它无法正常工作,而是显示:

id1 | id2

id2 | id1

id3 | id1

id1 | id3

id4 | id1

我希望输出是这样的:

id1 | id2

id3 | id1

id4 | id1

我可以看到出了什么问题,但如何解决它?

最佳答案

这是使用 least()greatest() 函数的好地方:

SELECT least(send_id, rec_id) as id1, greatest(send_id, rec_id) as id2
from inbox
WHERE send_id = 'id1' OR rec_id = 'id1'
GROUP BY least(send_id, rec_id), greatest(send_id, rec_id);

或者,如果您愿意的话:

SELECT distinct least(send_id, rec_id) as id1, greatest(send_id, rec_id) as id2
from inbox
WHERE send_id = 'id1' OR rec_id = 'id1';

关于php - 如何从表中删除重复/对应的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22583559/

相关文章:

php - Symfony3 将每次更新保存到数据库中

sql - 如果某个值更新列

sql - 加入具有相同列名的 2 个表时出现歧义列错误

php - WordPress 登录后将特定用户角色重定向到特定位置

php - 向用户显示以前上传的内容以供选择

mysql - 更新\插入数据从grafana到mysql

Mysql 选择执行和不执行的行

每年每季度的 MySQL 计数,计数为 0

sql - 查找字符串中是否有 6 位数字

php - 在最后出现的空格上拆分字符串