在写代码的时候突然想到一个问题,用in关键字查不出来东西怎么办? sql报错怎么办?
我在生产环境中用了如下的代码:
select * from cons_account where id in ( select cons_id from meter where run_status_code = '3' )
我想,如果in中的语句没有查出来东西,报错了怎么办?这么写合不合适?
自己试着在数据库写了一下:
select * from cons_account where id in ( )
果然报错:> 错误: 语法错误 在 ")" 或附近的
LINE 1: select * from cons_account where id in ( )
但是在生产环境中确认in中的sql查不出数据来也没有报错, 但是自己在数据库试了确实报错,这是怎么回事?
结论: 在in中用select查出来没有数据和在 in ()的括号中不写东西是两回事情。
在in()的括号中不写东西, 是语法错误。
而在in中的select 语句查不出结果来,实际返回的结果是null。
也就是说,哪怕select 查不出结果,实际的sql应该是这样的:
select * from cons_account where id in ( null )
这样的sql等价于:
select * from cons_account where id = null
这样的sql语句是没有问题的。