簡體   English   中英

使用 Join 時如何區分 select 記錄?

[英]How to select distinct records when using Join?

我有 3 個表,其結構如下:

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

//userTable
// userID, username, loginDate

//tagTable
// id, pid, tag

當一個新帖子發布時,用戶可以輸入多個標簽,每個標簽存儲在 tagTable 中的單獨一行中。

假設用戶輸入了 3 個標簽。

然后,一行進入 postTable,三行 go 在 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

我希望這只會 select 來自 postTable 的一條記錄,以及從 tagTable 輸入的 3 個標簽中的一個,然后它會跳到 postTable 中的下一行,忽略同一篇文章的其他 2 個標簽......

但它選擇 3 條記錄,全部重復,除了 t.* 的值

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

select postTable 中的帖子,select tagTable 中的一個標簽,然后跳到 postTable 中的下一行,忽略 tagTable 中已選擇的帖子中遺漏的 2 個標簽。

像不同的東西(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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM