如何使用UNION
合并来自两个表的JOIN
条记录。例如,假设我有以下表A和B,并希望最终得到表C.
我想提取和合并匹配tableB.Item ID
的所有tableA.Customer ID
,如果有多个匹配,那么我想创建一个新的字段来保存另一个。
//表A
Customer ID Customer_Bill_Name.......
XXX001 XXX Company Name......
XXX002 YYY Company Name......
//表B
Customer ID Item ID 1
XXX001 WH15 02
XXX001 600278
XX0002 600000
//表C:我想这样结束
Customer ID Customer_Bill_Name Item ID 1 Item ID 2
XXX001 XXX Company Name WH15 02 600278
XX0002 YYY Company Name 600000
以下是我用于使用JOIN
$result = mysqli_query($con,"SELECT Customers.CustomerId,
Customers.Customer_Bill_Name,
Customers.WhichShipVia,
JrnlHdr.INV_POSOOrderNumber,
JrnlHdr.ShipByDate,
JrnlHdr.GoodThruDate,
JrnlHdr.CustomerSONo,
JrnlHdr.Reference,
JrnlHdr.TransactionDate,
JrnlRow.DistNumber,
JrnlRow.Quantity,
LineItem.ItemID,
LineItem.SalesDescription,
LineItem.PartNumber,
LineItem.ItemDescription
FROM Customers
INNER JOIN JrnlHdr
ON Customers.CustomerRecordNumber = JrnlHdr.CustVendId
LEFT OUTER JOIN Address
ON Customers.CustomerRecordNumber = Address.CustomerRecordNumber
INNER JOIN JrnlRow // store sales order information
ON JrnlHdr.PostOrder = JrnlRow.PostOrder
LEFT OUTER JOIN BOMItems // stores Bill of Materials attached to the sales order
ON JrnlRow.ItemRecordNumber = BOMItems.AssemblyRecordNo
INNER JOIN LineItem //Stores all Inventory Items
ON JrnlRow.ItemRecordNumber = LineItem.ItemRecordNumber
WHERE JrnlHdr.JrnlKey_Journal = 11
AND JrnlHdr.PostOrder = JrnlRow.PostOrder
AND JrnlHdr.CustVendId = Customers.CustomerRecordNumber
AND JrnlRow.ItemRecordNumber = LineItem.ItemRecordNumber
AND JrnlHdr.POSOisClosed = 0
AND JrnlHdr.TransactionDate = '2014-11-17'
ORDER BY JrnlHdr.Reference,JrnlRow.DistNumber");
答案 0 :(得分:0)
也许您可以使用group_concat,这会将所有值连接到一列。
select a.*, group_concat(b.ItemId) joined
from tableA a inner join tableB b on a.customerId = b.customerId
group by a.customerId, a.customer, a.company
结果:
CUSTOMERID CUSTOMER COMPANY JOINED
XXX001 XXX Company Name 600278,WH15 02
XXX002 YYY Company Name 600000