如何选择可能包含交换字段的行?


How can I select a row that may contain swapped fields?

如何从表https://i.stack.imgur.com/27cu9.jpg中选择一行,其中'user_1'和'user_2'的值可能看起来像

user_1 user_2
  1      2
  2      1

换句话说,我想选择一个包含2个用户且submit =1的字段,无论该值在哪个字段

下面是一个简单的查询:

select *
from t
where submitted = 1 and 2 in (user_1, user_2)

如果我理解你的问题,我认为如果你试图返回具有相应用户(1,2)和(2,1)的行,你需要JOIN表本身:

select t1.*
from yourtable t1 
   join yourtable t2 on 
       t1.user_1 = t2.user_2 and t1.user_2 = t2.user_1
  • SQL Fiddle Demo

然而,如果你只是想看看用户2是否存在于其中一个字段,那么看看Gordon的帖子。

使用:-

       select * from tblname as t1, tblname as t2 where 
       t1.user_1 = t2.user_2 and t1.user_2 = t2.user_1 and t1.user_1<>t1.user_2

编辑:

更新查询,使具有相同值的行不出现在结果中。