简体   繁体   English

如何使用MySQL查询获取值?

[英]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. 我想在mysql查询中获取First_Name,LastName,First名字Last Name的所有记录。

For example, 例如,

mytable looks like this: mytable看起来像这样:

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. 给我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. 如果必须在查询中完成此操作,则可以使用GROUP_CONCAT ,但是除非您按某项进行分组,否则这是一个非常愚蠢的查询,并且串联实际上应该在客户端上完成。

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. 因此,我建议进行一个简单的SELECT查询,获取所需的记录,然后根据需要将它们排列在视图层中。

On the other hand, why do you need to solve this record concatenation at SQL level and not on view level? 另一方面,为什么需要在SQL级别而不是在视图级别解决此记录串联?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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