【mysql】五 不借用mybatis等框架的语句 实现另外表信息补充 基础表,实现 值为null、''时全条件查询(条件失效)

版权声明:转载请标明出处。 https://blog.csdn.net/u010720408/article/details/89520898

信息表补充

一:(不行)
select t1.*, t2.* from table1 t1,table2 t2 where t1.field1="xxx"  
这样的结果不行,例如 t1表中 field1="xxx" 中符合的10条,而t2 全表5条,那么会组合成 10*5=50条,不会自动根据相同字段名组合的。

二:(不行)
select t1.*,t2.* from table1 t1,table2 t2 where t1.field1="xxx" and t1.id=t2.id
这样的结果多了个t1.id=t2.id,如果只是相对t1记录,对应t2有信息则补充,那么t1.id 在t2.id中没有相等的则被过滤掉了,不符合补充信息的要求。

三:(ok)
select t1.*, (select field2 from table2 t2 where t2.id=t1.id limit 1 ) as field2,(select field3 from table2 t2 where t2.id=t1.id limit 1 ) as field3 where t1.field1="xxx"
注意:
     ①一次只能补充一个field信息,因为数据库就是这个模式,相当于 select t1.*,"变量值" from table1 t1 where t1.field="xxx"的形式,一次只能补一个字段,所以当要补充的字段特别多时很蛋疼。
     ②为何limit 1,防止多个值会报错
     ③为何还有 as field2  因为不重命名就列名就变成 哪个(select field2 from table2 t2 where t2.id=t1.id limit 1) 这个样子了,还怎么好好玩耍。
	 ④如果要补充的信息特别多、而且来自多个表,建议还是别再sql语句实现,因为你用 explain查看执行语句,每一个列补充信息就是子查询一次,性能不一定比得上在应用层分开查询补充信息。

实现 传入值 为null、""时放弃当前条件当全查询

一:(ok)
set @str=null;
select * from table1 where  @str is null or @str ='' or field like concat('%', @str, '%' );
注意:
      ①对null值只能用 is/is not 
      ②对‘’字符串,还是用=判定
      ③like concat('%',null,'%') 查不出任何值,也就是查不出值为null、‘’的记录
      ④like concat('%','','%') 查不出 值为null的值,但是对于''等其他字符串都能查出

猜你喜欢

转载自blog.csdn.net/u010720408/article/details/89520898