迭代两列并进行比较

时间:2016-05-04 09:02:34

标签: mysql sql stored-procedures

我有两个这样的栏目:

结果集1:select sPersonID from tPersonData where x < 50

结果集2:select sPersonID from tPersonData where x > 50

我希望重复第1列,并想检查第2列中每个sPeronID是否至少存在1次。

列的示例数据:

Result-Set 1:
00/510
00/650
00/644
00/690

Result-Set 2: 
00/510
00/640
00/644

预期结果应该为TRUE / FALSE

2 个答案:

答案 0 :(得分:1)

使用左连接自我加入tPersonData,并从左侧使用sPersonID分组,并从右侧计算相应记录的数量:

select t1.sPersonID, if(count(t2.sPersonID)=0,'false','true') as result
from tPersonData t1
left join tPersonData t2 on t1.sPersonID=t2.sPersonID and t2.x>50
where t1.x<50
group by t1.sPersonID

答案 1 :(得分:0)

你可以试试这个

select case
         when a = b then
          'TRUE'
         else
          'FALSE'
       end
  from (select (select COUNT(sPersonID)
                  from tPersonData t1
                 where t1.x < 50
                   AND t1.sPersonID IN
                       (select sPersonID from tPersonData where x > 50)) a,
               (select COUNT(sPersonID) from tPersonData t1 where t1.x < 50) b
          from dual)