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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM