mysql - 使用Join时如何选择不同的记录?

标签 mysql database string join group-by

我有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/

相关文章:

mysql - 您的 SQL 语法有错误;在 Joomla 中创建触发器

database - 需要比较 Firebird 中的 Blob

c - 如何在 C 中返回 ReadLine() 函数?

javascript - Express.js、mysql、通过一个属性分隔数据项

mysql - 喜欢...而不是...sql

java - JDBC PreparedStatement 始终返回 1 作为自动生成的键

sql - 创建一个已经存在的 SQL 表会覆盖它吗?

php - 将名称设置为数据库中的下拉列表?

java - JSONObject.put(String) 为每个 '\' 添加 '/'

在 C 中使用 printf 自定义字符串对齐