简体   繁体   中英

MySQL query multiple select and combine

I have a main table called MM(Material Movement) and a child one called MI(Material Items), I made a query to select all the MI records with a specific condition and each record in MI is connected to a master list table called stock, to get the item prices. now i need to get each of these items the account codes used to purchase. so i am back to the po (purchase order) table which also has a child called polines table, this polines table has the stockID which is in MI table as well.

MM
MMID , Sender, NewLocation,Status 

MI
MIID, MMID, StockID, Qty1

stock
StockID, Description, UPrice

polines
PLID, POID, StockID, UPrice, AccountCode


SELECT *
FROM (mm
JOIN mi ON mi.MMID = mm.MMID)
JOIN stock ON mi.StockID = stock.StockID
WHERE mm.Status = 'Issue'

above gives me the correct records like this (after selecting the columns i need not all) :

Sender  New Location  StockID  Description    UnitPrice
------  -----------   -------   ----------     ---------
James    DC1           A1       Generator g4     450

but what i need is this :

Sender  New Location  StockID     Description      UnitPrice    account code
------  -----------   ----------  ----------       ---------    ------------
James    DC1           A1         Generator g4       450         B001,B003

basically account code should be combined or grouped to the stockID but

this is what the polines table looks like:

StockID       Description    Account Code 
----------     -------       ----------   
   A1       Generator g4     B001
   A1       Generator g4     B003
   A2       Pipe D3          B004

I am not sure if this is possible in MySQL i could do it with PHP but i really want to advance my MySQL skills so any help would be appreciated!

use group_concat function

SELECT Sender,NewLocation,stock.StockID,polines.Description,UPrice, group_concat(polines .AccountCode separator ',')   
FROM mm
JOIN mi ON mi.MMID = mm.MMID
JOIN stock ON mi.StockID = stock.StockID
join polines on stock.StockID=polines.StockID
WHERE mm.Status = 'Issue'
group by Sender,NewLocation,UPrice,stock.StockID,polines.Description

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