MySQL query splicing
When using MySQL to query, sometimes you need to splice multiple fields or fields in multiple tables. In this case, you can use the string splicing function provided by MySQL to operate. Commonly used string concatenation functions include CONCAT, CONCAT_WS and GROUP_CONCAT.
CONCAT function is used to connect two or more strings or fields. The syntax is:
CONCAT(string1, string2, ...)
Among them, string1, string2 ... represents the string or field to be connected, which can be a constant, column name, expression, function, etc. For example, to find the name and position of an employee, you can use the following statement:
SELECT CONCAT(last_name, ' ', first_name) AS name, job_title FROM employees
The CONCAT function here concatenates last_name and first_name and separate them with spaces as a field name of the query result. The running results are as follows:
name | job_title |
---|---|
Geoni Bakewell | Production Manager |
Lemuel Marmie | Shipping Manager |
Lino Uselman | Engineer |
Honey Tunney | Sales Manager |
... | ... |
The CONCAT_WS function is also used for string concatenation, but unlike the CONCAT function, it can specify a delimiter. The syntax is:
CONCAT_WS(separator, string1, string2, ...)
Among them, separator represents the separator, which can be any string; string1, string2... represent the strings or fields to be connected, and multiple strings are separated by commas. For example, to find the full name and email address of an employee, you can use the following statement:
SELECT CONCAT_WS(' ', first_name, last_name) AS full_name, email FROM employees
The CONCAT_WS function here uses spaces as separators to concatenate first_name and last_name as a field full_name in the query result. The running results are as follows:
full_name | |
---|---|
Geoni Bakewell | gbakewell@classicmodelcars.com |
Lemuel Marmie | lmarmie@classicmodelcars.com |
luselman@classicmodelcars.com | |
htunney@classicmodelcars.com | |
... |
GROUP_CONCAT([DISTINCT] expr [,expr ...] [ORDER BY {unsigned_integer | col_name | expr} [ASC | DESC] [,col_name ...]] [SEPARATOR str_val])
SELECT department, GROUP_CONCAT(last_name ORDER BY employee_number ASC SEPARATOR ', ') AS employee_names FROM employees GROUP BY department
employee_names | |
---|---|
Murphy, Patterson, Bondur, Ferrante, Firrelli | ##Customer Service |
Finance | |
##... | |
The above is the detailed content of mysql query splicing. For more information, please follow other related articles on the PHP Chinese website!