我需要这个Mysql查询的帮助
Select id, code, Tbldetail from TblProd
结果是:
id code detail (i Need ADD Model Column Here)
100 432320-1 Keyboard
101 432325-1 Mouse
102 432329-1 Printer
我有另一个具有这种结构的表:
id code model
1 432320-1 rx1
2 432320-1 rx2
3 432320-1 rx3
4 432325-1 rx1
5 432329-1 rx2
6 432329-1 rx1
我需要这样的输出:
id code detail Model
100 432320-1 Keyboard rx1,rx2,rx3
101 432325-1 Mouse rx1
102 432329-1 Printer rx2,rx1
我该怎么做?
答案 0 :(得分:2)
这正是你在标题中所说的:
SELECT p.id, p.code, p.detail, GROUP_CONCAT(m.model ORDER BY m.model) as model
FROM TblProd AS p
LEFT JOIN TblModel AS m ON p.code = m.code
GROUP BY p.id
答案 1 :(得分:0)
有几种方法可以获得这种结果。
LEFT JOIN的一种替代方法是在SELECT列表中使用相关查询。
SELECT t.id
, t.code
, t.detail
, ( SELECT GROUP_CONCAT(DISTINCT r.model ORDER BY r.model)
FROM TblModel r
WHERE r.code = t.code
) AS model
FROM TblProd t
ORDER BY t.id
答案 2 :(得分:0)
SELECT a.id, a.code, a.detail, GROUP_CONCAT(b.model) as model
FROM TblProd AS a,TblModel AS b ON a.code = b.code
GROUP BY a.id