首先,这是表A,名字为building_device_ms,如下图:
,
然后表B,名字为ms_uploaddata,下图所示:
两张表之间,靠字段uid关联。现在我想用sql语句实现如下效果:根据表B的uid,如2290614309,找到对应的表A里的deviceid值,即3. 然后把表A中所有deviceid=3的uid的值拼接起来形成字段uids,这里即【2290614309、2290614311】,最后想要的结果如下:,问题在于:要保证表B里有几条记录,最后sql语句出来的结果就有几条,我的sql语句:
(1)
SELECT
tmp.deviceid,
tmp.uid,
REPLACE(group_concat(a.uid),',','、') as uids
FROM building_device_ms a
INNER JOIN
(SELECT b.deviceid ,c.uid FROM building_device_ms b
INNER JOIN ms_uploaddata c on b.uid = c.uid) tmp
on tmp.deviceid = a.deviceid
GROUP BY a.deviceid
分组时,由于deviceid都为3,给全部拼接了
(2)
SELECT DISTINCT
tmp.deviceid,
tmp.uid,
REPLACE(group_concat(a.uid),',','、') as uids
FROM building_device_ms a
INNER JOIN
(SELECT DISTINCT b.deviceid ,c.uid FROM building_device_ms b
INNER JOIN ms_uploaddata c on b.uid = c.uid) tmp
on tmp.deviceid = a.deviceid
GROUP BY a.deviceid
去重就保证不了记录数与表B一致。
综合起来——去重、分组保证不了记录数与表B一致,且分组会由于deviceid值相同,全部拼接了起来;不分组,uid拼接不起来,是不是我思路错了?希望有朋友耐心解决!~~万分感谢!