我有3个表,其结构如下:
//postsTable
// pid, userID, parentID, title, date
//userTable
// userID, username, loginDate
//tagTable
// id, pid, tag
当发布新帖子时,用户可以输入多个标签,每个标签存储在 tagTable 中的单独行中。
假设用户输入了 3 个标签。
然后,postTable 中放入一行,tagTable 中放入 3 行
当我选择时,我使用此查询:
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
关于mysql - 使用Join时如何选择不同的记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58650679/