php - mysql查询的问题,求帮助
滿天的星座
滿天的星座 2017-05-16 13:12:25
0
2
427

为了方便阐述问题 我简化的弄一张多对多的关系表 一共3个字段
id wid uid
现在希望能查出 在一组wid中 每个(不重复的)wid 下对应的 前5个uid(order by id limit 5)
即最后得出结果为
wid1 = [uid, uid, uid, uid ...]
wid2 = [uid, uid, uid, uid ...]
能不能直接用一条sql取出这样的结果呢?

滿天的星座
滿天的星座

reply all(2)
黄舟

Assume that the name of this table is tentatively demo_table
You can use the following statement to achieve your needs

SELECT
    wid,
    SUBSTRING_INDEX(GROUP_CONCAT(uid ORDER BY id),',',5) AS 'uids'
FROM demo_table
GROUP BY wid
左手右手慢动作

@deepgoing’s idea is okay. In order to solve the problem of uid duplication and sorting, you can first do a distcint query, such as:

SELECT
    wid,
    SUBSTRING_INDEX(GROUP_CONCAT(uid ORDER BY id),',',5) AS 'uids'
FROM (
  SELECT DISTINCT wid, uid
  FROM demo_table
  ORDER BY wid, uid
)
GROUP BY wid
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!