如何连接两个mysql表并将多行连接成单个单元格?

时间:2018-04-13 07:19:25

标签: php mysqli

如何连接两个sql表并将多行连接成单个单元格?

我正在使用的查询::

SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders
ON Customers.CustomerID=Orders.CustomerID;

我得到的输出::

客户名称OrderId

John Doe 101

John Doe 102

John Doe 103

John Doe 104

预期输出::

客户名称OrderId

John Doe 101,102,103,104

3 个答案:

答案 0 :(得分:1)

使用GROUP_CONCAT并按客户汇总以生成CSV订单列表:

SELECT
    c.CustomerName,
    GROUP_CONCAT(o.OrderID) AS OrderIDs
FROM Customers c
LEFT JOIN Orders o
    ON c.CustomerID = o.CustomerID
GROUP BY
    c.CustomerId;

请注意,如果可能,最好按客户ID进行汇总,因为可能有两个或更多客户具有相同的名称。

Demo

答案 1 :(得分:1)

组concat是实现所需输出的最简单方法。

答案 2 :(得分:0)

使用test <- function(x, ...) { # these are equivalent and print prints only its first argument, see ?print print(c(4,5,6), c(7,8,9), c(10,11,12)) print(...) # here's how you can get the dots a <- eval(substitute(alist(...))) # unevaluated dots # or a <- list(...) # evaluated dots (works fine as well in this case) a } test(x=c(1,2,3), c(4,5,6), c(7,8,9), c(10,11,12)) # [1] 4 5 6 # [1] 4 5 6 # [[1]] # c(4, 5, 6) # # [[2]] # c(7, 8, 9) # # [[3]] # c(10, 11, 12)

group_concat