Перейти к содержимому

Как складывать строки в sql mysql

  • автор:

Встроенные функции

Для работы со строка в MySQL определен ряд встроенных функций:

CONCAT : объединяет строки. В качестве параметра принимает от 2-х и более строк, которые надо соединить:

При этом в функцию можно передавать не только непосредственно строки, но и числа, даты — они будут преобразовываться в строки и также объединяться.

CONCAT_WS : также объединяет строки, но в качестве первого параметра принимает разделитель, который будет соединять строки:

LENGTH : возвращает количество символов в строке. В качестве параметра в функцию передается строка, для которой надо найти длину:

LTRIM : удаляет начальные пробелы из строки. В качестве параметра принимает строку:

RTRIM : удаляет конечные пробелы из строки. В качестве параметра принимает строку:

TRIM : удаляет начальные и конечные пробелы из строки. В качестве параметра принимает строку:

С помощью дополнительного оператора можно задать где имеено удалить пробелы: BOTH (в начале и в конце), TRAILING (только в конце), LEADING (только в начале):

LOCATE(find, search [, start]) : возвращает позицию первого вхождения подстроки find в строку search. Дополнительный параметр start позволяет установить позицию в строке search, с которой начинается поиск подстроки find. Если подстрока search не найдена, то возвращается 0:

LEFT : вырезает с начала строки определенное количество символов. Первый параметр функции — строка, а второй — количество символов, которые надо вырезать сначала строки:

RIGHT : вырезает с конца строки определенное количество символов. Первый параметр функции — строка, а второй — количество символов, которые надо вырезать сначала строки:

SUBSTRING(str, start [, length]) : вырезает из строки str подстроку, начиная с позиции start. Третий необязательный параметр передает количество вырезаемых символов:

SUBSTRING_INDEX(str, delimiter, count) : вырезает из строки str подстроку. Параметр delimiter определяет разделитель внутри строки. А параметр count определяет, до какого вхождения разделителя надо вырезать подстроку. Если count положительный, то подстрока вырезается с начала, если count отрицательный, то с конца строки str:

REPLACE(search, find, replace) : заменяет в строке find подстроку search на подстроку replace. Первый параметр функции — строка, второй — подстрока, которую надо заменить, а третий — подстрока, на которую надо заменить:

INSERT(str, start, length, insert) : вставляет в строку str, заменяя length символов с позиции start подстрокой insert. Первый параметр функции — строка, второй — позиция, с которой надо заменить, третий — сколько символов с позиции start надо заменить вставляемой подстрокой, четвертый параметр — вставляемая подстрока:

REVERSE : переворачивает строку наоборот:

LOWER : переводит строку в нижний регистр:

UPPER : переводит строку в верхний регистр

SPACE : возвращает строку, которая содержит определенное количество пробелов

REPEATE(str, count) : возвращает строку, которая содержит определенное количество повторов подстроки str. Количество повторов задается через параметр count.

LPAD(str, length, pad) : добавляет слева от строки str некоторое количество символов, которые определены в параметре pad. Количество добавляемых символов вычисляется по формуле length — LENGTH(str) . Если параметр length меньше длины строки str, то эта строка усекается до length символов.

RPAD(str, length, pad) : добавляет справа от строки str некоторое количество символов, которые определены в параметре pad. Количество добавляемых символов вычисляется по формуле length — LENGTH(str) . Если параметр length меньше длины строки str, то эта строка усекается до length символов.

MySQL функция CONCAT

MySQL функция CONCAT позволяет объединять вместе два или более выражений.

Синтаксис

Синтаксис MySQL функции CONCAT:

Параметры или аргументы

expression1 , expressoin2 , . expression_n выражения для объединения.

Примечание

  • Если expression является числовым значением, то оно будет преобразовано функцией CONCAT в двоичную строку.
  • Если все expressions не являются двоичными строками, функция CONCAT вернет недвоичную строку.
  • Если какое-либо из expressions является двоичной строкой, функция CONCAT вернет двоичную строку.
  • Если какое-либо из выражений имеет значение NULL, функция CONCAT вернет значение NULL.
  • См. Также функцию CONCAT_WS.

Применение

Функция CONCAT может использоваться в следующих версиях MySQL:

  • MySQL 5.7, MySQL 5.6, MySQL 5.5, MySQL 5.1, MySQL 5.0, MySQL 4.1, MySQL 4.0, MySQL 3.23

Пример

Рассмотрим примеры MySQL функции CONCAT, чтобы понять, как использовать функцию CONCAT в MySQL.
Например:

MySQL CONCAT() function

MySQL CONCAT() function is used to add two or more strings.

  • There may be one or more arguments.
  • Returns the string that results from concatenating the arguments.
  • Returns a nonbinary string, if all arguments are nonbinary strings.
  • Returns a binary string, if the arguments include any binary strings.
  • If the argument is numeric, it is converted to its equivalent nonbinary string form.
  • Returns NULL if any argument is NULL.

Syntax:

Arguments:

Name Description
string1 First string to be joined.
string2 Second string to be joined. Up to N number of strings can be specified this way.

Syntax Diagram:

MySQL CONCAT() Function - Syntax Diagram

MySQL Version: 5.6

Pictorial representation of MySQL CONCAT() function

pictorial representation of MySQL CONCAT function

Video Presentation:

Your browser does not support HTML5 video.

Examples: MySQL Concat() Function

Table of Contents :

Example of MySQL Concat Function using agruments

One argument:

Two or more arguments:

One of the arguments is NULL :

Numeric argument:

For quoted strings, concatenation can be performed by placing the strings next to each other :

Example of MySQL CONCAT() function on columns

The following MySQL statement will add values of pub_city column with values of the country column of publisher table placing a ‘—>’ between them.

Code:

Sample table: publisher

Sample Output:

MySQL CONCAT using WHERE clause

The following MySQL statement will add pub_city and country column by a ‘—>’ for those publishers whose concatinated name and country office is ‘Ultra Press Inc. London’

Code:

Sample table: publisher

Sample Output:

MySQL CONCAT returns NULL if any field contain NULL

The following MySQL statement will add book name and pub_lang column by a ‘—>’ for all the books.

Code:

Sample table: book_mast

Sample Output:

The above output shows that, when the value of any of the two columns mention above is NULL, the output returns NULL, mention by red color.

MySQL CONCAT using JOINS and wildcard character

The following MySQL statement will show the combination of first name and last name and job title for those employees who contains the word Smith to their first and last name combination.

Code:

Sample table: employees

Sample table: jobs

Sample Output:

PHP Script:

JSP Script

Try the following Queries

Write a SQL statement to display the publisher city and name according to the group on publisher city.

Write a SQL statement to display the publisher city and name and country office with a suitable title for those publishers which country office and publishing city are in the same place.

Write a SQL statement to display the publisher name, country office and a maximum number of branches with the suitable title for those publishers who maintain on and above 15 branches worldwide.

Sample table : publisher

MySQL Online Editor

1.
SELECT CONCAT(pub_city,’ — ‘,pub_name)
FROM publisher
GROUP BY pub_city;
2.
SELECT CONCAT(‘City:- ‘,pub_city,’ Publisher Name :- ‘,pub_name,’ Country Office :- ‘,country_office)
FROM publisher
WHERE pub_city=country_office
GROUP BY pub_city;
3.
SELECT CONCAT(‘Publisher Name :- ‘,pub_name,
‘Country Office:- ‘,country_office,
‘Highest Branches:- ‘,Max(no_of_branch))
FROM publisher
GROUP BY pub_name
HAVING Max(no_of_branch)>=15;

Want to practice more MySQL exercises? Click here to get three hundred plus exercises with solutions.

Previous: CONCAT_WS
Next: ELT

Follow us on Facebook and Twitter for latest update.

  • Weekly Trends

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook

Как складывать строки в sql 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. If a numeric argument is given then it is converted to its equivalent nonbinary string form. Syntax :

Parameter : This method accepts N argument.

  • str1, str2.str3…. : The input string which we want to concatenate.

Returns : It returns a new string after concatenating all input string. If any of the input string is NULL then it returns NULL. Example-1 : Concatenating 3 string using CONCAT Function.

Output :

ConcatenatedString
geeksforgeeks

Example-2 : Concatenating numeric string using CONCAT Function.

Output :

ConcatenatedNumber
19105.60

Example-3 : Concatenating string which includes a NULL String using CONCAT Function.

Output :

ConcatenatedString
NULL

Example-4 : In this example we are going to concatenate string between column of a table. To demonstrate create a table named Student.

Now inserting some data to the Student table :

So, the Student table is :

StudentId FirstName LastName Class City State PinNo
1 Sayantan Maity X Kolkata WestBengal 700001
2 Nitin Shah XI Jalpaiguri WestBengal 735102
3 Aniket Sharma XI Midnapore WestBengal 721211
4 Abdur Ali X Malda WestBengal 732101
5 Sanjoy Sharama X Kolkata WestBengal 700004

Now, we will concatenate FirstName and LastName to get FullName and City, State and PinNo to get Address using CONCAT Function.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Car Rental HPN Inside the Terminal