这是小提琴;
http://sqlfiddle.com/#!2/af8015/9

我有一些数据,我想设置


如果user和g参数在名为cl的表中,则结果列应
是1;
如果user和g参数在名为im的表中,但不在cl的表中,则结果
列应为-1;
否则,结果列应为0


我正在使用以下查询;

select *,
    case cl.user_id
       when null then -1
       when im.user_id then 1
    end as result
from im
left join cl     on cl.user_id = im.user_id
                and cl.id_g = im.id_g
left join user   on user.user_id = im.user_id
left join g      on g.id_g = im.id_g


但是,它为-1返回null,而我无法为最后一种情况设置0。

预期结果表为;

user id - g id - result
  1         1     1
  1         2     1
  1         3     0
  1         4     1
  2         1     1
  2         2     1
  2         3    -1
  2         4     0
...

最佳答案

我看不到从样本数据生成0结果的方法。

我相信您的result参数应该这样计算;

IF (cl.user_id IS NOT NULL and cl.id_g IS NOT NULL, 1,
    IF(im.user_id IS NOT NULL and im.id_g IS NOT NULL, -1,0)
   ) result


而且,我认为您的一系列JOIN操作应该是这样的。

FROM user
LEFT JOIN im ON user.user_id = im.user_id
LEFT JOIN cl ON user.user_id = cl.user_id AND im.id_g = cl.id_g
LEFT JOIN g  ON im.id_g = g.id_g


也就是说,您应该以user表开头。这是一个示例:http://sqlfiddle.com/#!2/a5c6ef/1/0

您的result参数的计算如下:

 case cl.user_id
    when null then -1
    when im.user_id then 1
 end as result


null值工作异常。一个null值永远不能等于任何东西,甚至不能等于另一个null值,因此when null then -1永远不会触发。另一方面,这种表达应该起作用。

 case when cl.user_id IS NULL then -1
      when im.user_id IS NULL then 1
      else 0 end as result

关于mysql - SQL查询以设置值(如果存在数据),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28738878/

10-11 06:38
查看更多