MySQL左连接获得双重结果

时间:2017-11-02 04:47:28

标签: mysql sql

我的查询有问题。首先这是我的数据库结构

database mt
- mtnobuk
- mtbrg
- mtcolor
- mtloc

database mv
- mvnobuk
- mvrng
- mvmsn
- mtnobuk (FK)

这是我的数据 -

MT
mtnobuk     mtbrg   mtcolor     mtloc
---------------------------------------------
MT-112      Shape    Blue       L1

MV
mvnobuk     mvrng   mvmsn       mtnobuk
-------------------------------------------------
MV-111      round   sharp       MT-112
MV-112      oval    blunt       MT-112

我想要的只是我想查询我的数据 -

mtnobuk     mtbrg       mtcolor       mvrng         mvmsn
----------------------------------------------------------
MT-112      Shape        Blue         round         sharp
                                      oval          blunt
----------------------------------------------------------

到目前为止我已经尝试了

SELECT  mtnobuk,mtbrg,mtcolor,mtloc,mvnobuk,mvrng,mvmsn,mtnobuk
FROM    mv
LEFT JOIN mt on mtnobuk = mvnobuk
WHERE mtnobuk = MT-112
GROUP BY mtnobuk,mtbrg

我已经尝试了很多次,而且我得到的只是双重结果,就像这样

mtnobuk     mtbrg       mtcolor       mvrng         mvmsn
----------------------------------------------------------
MT-112      Shape        Blue         round         sharp
                                      oval          blunt
----------------------------------------------------------
MT-112      Shape        Blue         round         sharp
                                      oval          blunt
----------------------------------------------------------

我希望有人可以帮我解决这个问题,谢谢你们,祝你们度过愉快的一天。

2 个答案:

答案 0 :(得分:2)

我认为GROUP CONCAT可能是你能做的最好的。试试这样:

SELECT  mtnobuk, mtbrg, mtcolor, mvnobuk, GROUP_CONCAT(mvrng), GROUP_CONCAT(mvmsn)
FROM    mv
LEFT JOIN mt on mtnobuk = mvnobuk
WHERE mtnobuk = MT-112
GROUP BY mtnobuk, mtbrg, mtcolor, mvnobuk

答案 1 :(得分:1)

试试这个:

 SELECT  mt.mtnobuk, mt.mtbrg, mt.mtcolor, mv.mvnobuk, GROUP_CONCAT(mv.mvrng) as mvrng , GROUP_CONCAT(mv.mvmsn) as mvmsn
FROM    mv
LEFT JOIN mt on mt.mtnobuk = mv.mtnobuk
WHERE mt.mtnobuk = "MT-112"
GROUP BY mt.mtnobuk