简体   繁体   中英

How to fetch values with a MySQL query?

I want to fetch all the records of First_Name, LastName, First Name Last Name in a mysql Query.

For example,

mytable looks like this:

rec Id      First Name     Last Name
1           Gnaniyar       Zubair
2           Frankyn        Albert
3           John           Mathew
4           Suhail         Ahmed

Output should be like this:

Gnaniyar Zubair, Frankyn Albert, John Mathew, Suhail Ahmed

Give me the SQL.

If this must the done in the query, you can use GROUP_CONCAT , but unless you're grouping by something it's a pretty silly query and the concatenation should really be done on the client.

SELECT GROUP_CONCAT(FirstName + ' ' + LastName
                    ORDER BY FirstName, LastName
                    SEPARATOR ', ') AS Names
FROM People;

It is not a matter of getting one row with all the records, but a matter of representation of data. Therefore, I suggest to take a simple SELECT query, take the records you need, then arrange them in the view layer as you like.

On the other hand, why do you need to solve this record concatenation at SQL level and not on view level?

If you wanted to get them in just one row, you're probably not using your database properly.

If you just want to join together the first and last names, that's easy:

 SELECT CONCAT(`First Name`, ' ', `Last Name`) FROM mytable

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM