Given the table Test:
| id | name | last_name |
---------------------------
| 1 | hello | world |
| 2 | hello | world1 |
| 1 | foo | bar |
How can I select the distinct values from the name column and concatenate it with an prefix?
The preferred output would be:
| prefix_hello |
| prefix_foo |
I tried the following query, which doesn't work:
Select CONCAT("prefix_", DISTINCT(a.name)) from Test a
use group by:
select CONCAT("prefix_", a.name)
from Test a
group by a.name
Need to update your query like this
SELECT DISTINCT CONCAT('prefix_', name) nameFROM `test`
Note When only one expression is provided in the DISTINCT clause, the query will return the unique values for that expression. When more than one expression is provided in the DISTINCT clause, the query will retrieve unique combinations for the expressions listed. In MySQL, the DISTINCT clause doesn't ignore NULL values. So when using the DISTINCT clause in your SQL statement, your result set will include NULL as a distinct value.
OR
you can use group by
select CONCAT("prefix_", name)
from Test
group by name
for more information https://www.w3schools.com/sql/sql_distinct.asp
Select DISTINCT CONCAT("prefix_", a.name) from Test a
It's a common misunderstanding that DISTINCT is a function. It's not — it's a query modifier. It must follow SELECT. Then after DISTINCT, you can use any conventional select-list of expressions.
Schema and insert statements:
create table Test( id int, name varchar(50), last_name varchar(50));
insert into Test values(1 , 'hello' , 'world');
insert into Test values(2 , 'hello' , 'world1');
insert into Test values(1 , 'foo' , 'bar' );
Query#1 To get distinct names with prefix in a single rows as comma separated string:
select group_concat( distinct concat('prefix_',name)) Names
from Test a
Output:
Names |
---|
prefix_hello,prefix_foo |
Query#2 To have Distinct names in with prefix separate rows in a column.
Select DISTINCT CONCAT("prefix_", a.name)Names from Test a
Output:
Names |
---|
prefix_hello |
prefix_foo |
db<>fiddle here
select CONCAT("prefix_", T1.name) from (select distinct(a.name) as name from test)T1;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.