首页 > 解决方案 > 使用 Join 时如何选择不同的记录?

问题描述

我有 3 个表,其结构如下:

//postsTable
// pid, userID, parentID, title, date

//userTable
// userID, username, loginDate

//tagTable
// id, pid, tag

当一个新帖子发布时,用户可以输入多个标签,每个标签存储在 tagTable 中的单独一行中。

假设用户输入了 3 个标签。

然后,一排进入postTable,三排进入tagTable

当我选择时,我正在使用这个查询:

select p.*, c.*, t.* 
from postTable as p 
join userTable as c 
on p.userID = c.userID 
join tagTable as t 
on p.pid = t.pid
where p.parentID='0' 
order by p.date desc limit 10

我希望这只会从 postTable 中选择一条记录,并从 tagTable 输入的 3 个标签中选择一个,然后它会跳到 postTable 中的下一行,忽略同一篇文章的其他 2 个标签...

但它选择 3 条记录,全部重复,除了 t.* 的值

基本上,这就是我想要的。

从 postTable 中选择帖子,然后从 tagTable 中选择一个标签,然后跳到 postTable 中的下一行,对于已选择的帖子,忽略 tagTable 中遗漏的 2 个标签。

类似 distinct( p.pid )、c.userID、c.username、t.tag

我在这里做错了什么?

标签: mysqldatabasestringjoingroup-by

解决方案


与其从可用于帖子的标签中随机选择一个标签,一个明智的选择是使用聚合和group_concat(). 这将为每个帖子提供一条记录,以及相关标签的逗号分隔列表:

select
    p.pid, 
    p.userID,
    p.parentID,
    p.title,
    p.date,
    u.userID,
    u.username,
    u.loginDate,
    group_concat(t.tag order by t.tag) tags
from 
    postTable as p 
    inner join userTable as u on on p.userID = u.userID 
    inner join tagTable as t on p.pid = t.pid 
where p.parentID = '0'
group by
    p.pid, 
    p.userID,
    p.parentID,
    p.title,
    p.date,
    u.userID,
    u.username,
    u.loginDate
order by p.date
limit 10

推荐阅读