Use GROUP_CONCAT() to perform group concatenation and set a condition. Let us first create a table −
mysql> create table DemoTable813( UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY, UserFirstName varchar(100), UserLastName varchar(100) ); Query OK, 0 rows affected (0.49 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable813(UserFirstName,UserLastName) values('Adam','Smith'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable813(UserFirstName,UserLastName) values('Chris','Brown'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable813(UserFirstName,UserLastName) values('David','Miller'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable813(UserFirstName,UserLastName) values('Carol','Taylor'); Query OK, 1 row affected (0.22 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable813;
This will produce the following output −
+--------+---------------+--------------+ | UserId | UserFirstName | UserLastName | +--------+---------------+--------------+ | 1 | Adam | Smith | | 2 | Chris | Brown | | 3 | David | Miller | | 4 | Carol | Taylor | +--------+---------------+--------------+ 4 rows in set (0.00 sec)
Following is how to group concatenate and display only the last names −
mysql> select group_concat(UserLastName) from DemoTable813 where UserId < 4;
This will produce the following output −
+----------------------------+ | group_concat(UserLastName) | +----------------------------+ | Smith,Brown,Miller | +----------------------------+ 1 row in set (0.00 sec)