mysql根据条件合并多行,并将结果连接到一个字段中

euoag5mw  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(376)

我在mysql中构建查询时遇到了一些困难,无法根据条件组合多行结果并将结果连接到一个字段中。我有以下表格结构:
表1:客户

customerID     feature_1       feature_2    feature_3
==========    =============    =========    =========
1             administrator    active       1000
2             moderator        blocked      9999

表2:订单详情

OrderID       customerID    OrderDate       OrderdetailsName      OrderdetailsData
==========    ==========    ==========      ================      ================
1              1             1/1/2018       firstname             John
1              1             1/1/2018       lastname              Dow
1              1             1/1/2018       phone                 111111
2              2             2/1/2018       firstname             George
2              2             2/1/2018       lastname              Smith
2              2             2/1/2018       phone                 222222

两个表中的数据都由“customerid”字段链接
我想查询以下结果:

OrderID   OrderDate    customerID    feature_3    FullName
=======   =========    ============  =========    ============
1         1/1/2018     1             1000         John Dow
2         2/1/2018     2             9999         George Smith

我的问题是如何使查询在单个字段中获得结果全名,因为它的数据/详细信息基于给定的元标记名(列'orderdetailsname'-firstname或lastname)存储在多行中
非常感谢您的帮助!

m1m5dgzv

m1m5dgzv1#

使用有条件的组concat应该有效

SELECT customers.feature_3, orderdetails.OrderID, orderdetails.OrderDate, 
orderdetails.customerID, GROUP_CONCAT(if(orderdetails.OrderdetailsName = 'firstname' || 
orderdetails.OrderdetailsName = 'lastname', orderdetails.OrderdetailsData, '') SEPARATOR ' ') 
as fullname FROM customers join orderdetails on customers.customerID = 
orderdetails.customerID GROUP by customerID

相关问题