Mysql查询以映射表的顺序返回结果

时间:2016-08-24 12:01:37

标签: mysql

我有一个表A_B映射。现在我想要那些只与单个B相关联的A.

A    B
12  16
12  22
12  23
12  26
23  16
24  26

假如我是否会搜索与B = 16相关联的A,我会得到12和23 A. 但我只想要23,因为它只与B = 16相关联。

第二个选择可以是先23然后将发生12。 因此,首要任务是单个关联项,然后会发生多个关联。

2 个答案:

答案 0 :(得分:0)

1

select A
  from test4 T1
 where B=16
   and not exists(select 1 from test4 T2
                   where T2.A=T1.A and T2.B<>T1.B)

2

select A 
  from test4 T1
 where B=16
 order by exists(select 1 from test4 T2
                  where T2.A=T1.A and T2.B<>T1.B)

答案 1 :(得分:0)

你的意思是?

Select A FROM A_B where B IN (Select B FROM A_B where A=12) and A<>'12'