mysql的合并字段,并根据where查询合并后的字段

 mysql合并字段一般使用Concat和Concat_ws这个方法,下面就是它的区别:

1、concat函数可以连接一个或者多个字符串,如:

select concat('11','22','33');--112233

注: MySQL的concat函数在连接字符串的时候,只要其中一个是NULL,那么将返回NULL

2、concat_ws()函数

select concat_ws(',','11','22','33');--11,22,33

select concat_ws('|','11','22','33');--11|22|33

和concat不同的是, concat_ws函数在执行的时候,不会因为NULL值而返回NULL

3、group_concat()函数,可用来行转列

create table aa(
  id int,
  name VARCHAR(255)
);

insert  into aa values(1,10);
insert  into aa values(1,10);
insert  into aa values(1,20);
insert  into aa values(1,30);
insert  into aa values(3,30);
insert  into aa values(5,60);
insert  into aa values(5,90);
insert  into aa values(6,990);

1 以id分组,把name字段的值打印在一行,逗号分隔(默认)
select id,group_concat(name) from aa group by id;

2 以id分组,把name字段的值打印在一行,分号分隔
select id,group_concat(name separator ';') from aa group by id;

3 以id分组,把去冗余的name字段的值打印在一行,逗号分隔
select id,group_concat(distinct name separator ';') from aa group by id;

4 以id分组,把name字段的值打印在一行,*号分隔,以name排倒序
select id,group_concat(name order by name desc separator "*") from aa group by id;

 

 

 

mysql的合并字段,并根据where条件查询合并后的字段

我们在做项目的时候有可能遇到查询合并后的字段:

select * from prospect WHERE concat_ws(' ',first_name,last_name) LIKE '%Lam Family3%'; --查询出有Lam Family3的字段

转化成thinkphp的代码是:

$full_name = Client::whereRaw("concat_ws(' ',first_name,last_name) LIKE '%$search%'")->select();

 

 

 

 

参考链接:https://blog.csdn.net/vasilis_1/article/details/75305473

posted @ 2020-12-12 16:15  不睡  阅读(2962)  评论(0编辑  收藏  举报