mysql - 选择不同的 2 列

标签 mysql sql rdbms

我有下表:ID1、ID2、姓名、性别

表中存在 ID1 重复但 ID2、姓名和性别不同的记录 -- 也存在 ID2 重复但 ID1、姓名和性别不同的记录。 ID1 和 ID2 都可以有空值,但同一条目不能有空值。 我需要为 id1 和 id2 选择不重复的记录,例如

id1   id2      name    sex
10     null    jack     M
10     null    tom      M
null   40      jennie   F
null    32     jenie    F
null    32     emma     M
10     null    stevie   M

需要选择查询才能返回:

id1   id2     name     sex
10     any    any      any (any means it can be either jack,tom,stevie)
null   40     jennie   F
null   32     any      any2 (any2 meaning jeniw or emma)

最佳答案

您可以在 WHERE 子句中使用 EXISTS:

select t1.id1,
  t1.id2,
  name,
  sex
from yourtable t1
where exists (select *
              from yourtable t2
              where t1.id1 = t2.id1
               or t1.id2 = t2.id2)
group by t1.id1, t1.id2

参见SQL Fiddle with Demo

关于mysql - 选择不同的 2 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12150503/

相关文章:

relational-database - 什么是部分依赖

asp.net - 如何用Asp.net 2008连接Mysql服务器

SQL Server 舍入错误,给出不同的值

mysql - mysql 表 (MyISAM) 中的索引如何工作?

sql - 如何将 SQL 查询中字段的结果更改为仅包含第一个下划线之前的字符?

php - Sql 字符串查询不起作用

sql-server - 聚集索引在哪里存储中间级别键的行数据?

mysql - 从用户端将播放列表设为公开或私有(private)

python - django taggit similar_objects 查询非常慢

mysql - ruby ,MySQL2 : check if the result is empty