mysql - 使用 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
我在这里做错了什么?
解决方案
与其从可用于帖子的标签中随机选择一个标签,一个明智的选择是使用聚合和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
推荐阅读
- javascript - 发送到客户端 axios next.js 后无法设置标头
- reactjs - 使用包含多个 CN 或域名的 SSL 托管 asp.net core + ReactJS Web 应用程序导致无效的颁发者错误
- javascript - 将动态字符串传递给对象
- python - 如何使用经过训练的 pyod.LOCI 和机器学习模型预测给定值是否异常?
- pyspark - 动态构建 Pyspark 语法
- javascript - 无法在电子中打印闪存应用程序
- python-3.x - 烧瓶没有响应模板
- javascript - 在“react”渲染中使用迭代语句创建表
- c# - 如何使用 HtmlAgilityPack 对特定节点之间的所有内部文本进行上下文感知解析
- elasticsearch - Elasticsearch - 如何索引计算字段?