【问题标题】:How to select distinct records when using Join?使用 Join 时如何选择不同的记录?
【发布时间】:2020-02-27 05:54:31
【问题描述】:

我得到了 3 个结构如下的表:

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

//userTable
// userID, username, loginDate

//tagTable
// id, pid, tag

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

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

然后,postTable 中放 1 行,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 by,但您必须添加类似 MIN(Ttag) 的内容,或者如果您希望所有标签使用 GROUP_CONCAT。其余的我们相等而不是在 Grou By 中,您可以使用 MIN 但对于标签,您必须从这些 dev.mysql.com/doc/refman/8.0/en/group-by-functions.html 中选择一个
  • 它不工作。我用 group_concat( t.tag ) 替换了 "t.*",然后在 "order by p.date,我添加了这个 "group by p.pid" 之后,现在我收到一个 mysql 错误,说 "检查 mysql 手册在“group by p.pid”附近使用正确的语法

标签: mysql database string join group-by


【解决方案1】:

与其从可用于帖子的标签中随机选择一个标签,不如使用聚合和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

【讨论】:

  • 这行得通,但我还有一个问题。 postTable 上的索引如下 INDEX(userID, parentID)。该查询是否遵循该索引?我问是因为在加入 tagTable 后 parentID='0' 即将结束。
  • @SumitKumar:给定joinwhere 条件,我会假设MySQL 会使用该索引。但唯一可以确定的方法是检查查询的执行计划。
  • 好的。感谢您的帮助。这很棒。我只是在学习使用连接语句,直到现在都在使用旧方法,将所有内容都放在 where 子句中...您的解决方案有效:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-27
  • 1970-01-01
相关资源
最近更新 更多