php MySQL,连接两列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10346302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 21:58:15  来源:igfitidea点击:

MySQL, Concatenate two columns

phpmysqlsql

提问by Chandra Sekhar Biswal

There are two columns in a MySQL table: SUBJECTand YEAR.

MySQL 表中有两列:SUBJECTYEAR

I want to generate an alphanumeric unique number which holds the concatenated data from SUBJECT and YEAR.

我想生成一个字母数字唯一编号,其中包含来自 SUBJECT 和 YEAR 的连接数据。

How can I do this? Is it possible to use a simple operator like +?

我怎样才能做到这一点?是否可以使用像+?

回答by Mischa

You can use the CONCATfunction like this:

您可以CONCAT像这样使用该函数:

SELECT CONCAT(`SUBJECT`, ' ', `YEAR`) FROM `table`

Update:

更新:

To get that result you can try this:

要获得该结果,您可以尝试以下操作:

SET @rn := 0;

SELECT CONCAT(`SUBJECT`,'-',`YEAR`,'-',LPAD(@rn := @rn+1,3,'0'))
FROM `table`

回答by Shafiqul Islam

You can use php built in CONCAT() for this.

为此,您可以使用 CONCAT() 中内置的 php。

SELECT CONCAT(`name`, ' ', `email`) as password_email FROM `table`;

change filed name as your requirement

根据您的要求更改归档名称

then the result is

那么结果是

enter image description here

在此处输入图片说明

and if you want to concat same filed using other field which same then

如果您想使用其他相同的字段连接相同的文件,那么

SELECT filed1 as category,filed2 as item, GROUP_CONCAT(CAST(filed2 as CHAR)) as item_name FROM `table` group by filed1 

then this is output enter image description here

然后这是输出 在此处输入图片说明

回答by Vasanth

In php, we have two option to concatenate table columns.

在 php 中,我们有两个选项来连接表列。

First Option using Query

使用查询的第一个选项

In query, CONCATkeyword used to concatenate two columns

在查询中,CONCAT关键字用于连接两列

SELECT CONCAT(`SUBJECT`,'_', `YEAR`) AS subject_year FROM `table_name`;

Second Option using symbol ( . )

使用符号 ( . ) 的第二个选项

After fetch the data from database table, assign the values to variable, then using ( . ) Symboland concatenate the values

从数据库表中获取数据后,将值分配给变量,然后使用( . ) 符号并连接值

$subject = $row['SUBJECT'];
$year = $row['YEAR'];
$subject_year = $subject . "_" . $year;

Instead of underscore( _ ) , we will use the spaces, comma, letters,numbers..etc

我们将使用空格、逗号、字母、数字等代替下划线(_)

回答by Saravanan

$crud->set_relation('id','students','{first_name} {last_name}');
$crud->display_as('student_id','Students Name');