簡體   English   中英

關於多對多關系的單一SQL查詢

[英]Single SQL query on many to many relationship

我有一個簡單的數據庫,有幾個表(和一些示例列):

帖子 (ID,標題,內容)

類別 (ID,標題)

PostCategories (ID,ID_Post,ID_Category)

有沒有辦法創建單個SQL查詢,它將返回分配給每個帖子的類別的帖子?

您可以使用GROUP_CONCAT函數

select p.*, group_concat(DISTINCT c.title ORDER BY c.title DESC SEPARATOR ', ')
from Posts p
inner join PostCategories pc on p.ID = pc.ID_Post
inner join Categories c on pc.ID_Category = c.ID
group by p.id, p.title, p.content

簡單的連接工作得很好。

SELECT posts.id, posts.title, categories.id, categories.title
FROM posts
JOIN posts_categories ON posts.id = posts_categories.post_id
JOIN categories ON posts_categories.category_id = categories.id
select p.*, c.*
from Posts p
inner join PostCategories pc on p.ID = pc.ID_Post
inner join Categories c on pc.ID_Category = c.ID

如果你的意思是每個帖子只有一個記錄,我將需要知道你正在使用什么數據庫平台。

當然。 如果我正確理解你的問題,那應該就這么簡單

SELECT Posts.title, Categories.title 
FROM Posts, Categories, PostCategories 
WHERE PostCategories.ID_Post = Posts.ID AND PostCategories.ID_Category = Categories.ID 
ORDER BY Posts.title, Categories.title;

每個Post獲得一行會稍微復雜一點,並且取決於你正在使用的RDBMS。

我們也可以使用這個查詢。

select e.*,c.* from Posts e, Categories c, PostCategories cp where cp.id in ( select s.id from PostCategories s where s.empid=e.id and s.companyid=c.id );

暫無
暫無

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

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