Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL, Concatenate two columns

Tags:

sql

php

mysql

There are two columns in a MySQL table: SUBJECT and YEAR.

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

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

like image 518
Chandra Sekhar Biswal Avatar asked Apr 27 '12 07:04

Chandra Sekhar Biswal


People also ask

How do I concatenate two columns in SQL?

Query: SELECT *, CONCAT(FIRSTNAME, LASTNAME) AS FIRSTNAME FROM demo_table; Output: Here, we can see that FIRSTNAME and LASTNAME is concatenated but there is no space between them, If you want to add space between the FIRSTNAME and LASTNAME then add space(' ') in CONCAT() function.

How do you concatenate in MySQL?

CONCAT() function in MySQL is used to concatenating the given arguments. It may have one or more arguments. If all arguments are nonbinary strings, the result is a nonbinary string. If the arguments include any binary strings, the result is a binary string.


1 Answers

You can use the CONCAT function like this:

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` 
like image 79
Mischa Avatar answered Sep 23 '22 14:09

Mischa