我試圖拉取存在於幾個不同表格中的數據。具體來說,我有一個bug表,以及一個關於這些bug的「posts」(註釋/更新)表。對於每個錯誤,可能沒有評論,一條評論或很多。我希望返回所有錯誤,並返回所有評論(儘管我想省略更新),但是作爲列,而不是每個錯誤/評論一行。一對多關係 - 一個項目有很多評論
這裏就是我開始:
select
b.bg_id,
b.bg_reported_date as "Date Created",
b.bg_short_desc as "Summary",
bp.bp_comment_search as "Comment Body",
s.st_name as "Status",
p.pr_name as "Priority",
bp.bp_type as "Update Type"
from
bugs b
inner join bug_posts bp on b.bg_id = bp.bp_bug
inner join statuses s on b.bg_status = s.st_id
inner join priorities p on b.bg_priority = p.pr_id
--where bp.bp_type = 'comment'
order by b.bg_id asc
這給了我一個排爲每個評論,這不是我想要的。正如你所看到的,我還試圖限制結果只包括「評論」類型的帖子,但是這排除了沒有評論的任何錯誤,所以我把它解決了。
我發現這篇文章似乎其相關:JOIN in SQL with one-to-many relationship
但我不能把它與我的查詢工作。這是我到目前爲止:
select
b.bg_id,
b.bg_reported_date as "Date Created",
b.bg_short_desc as "Summary",
--bp.bp_comment_search as "Comment Body",
s.st_name as "Status",
p.pr_name as "Priority",
--bp.bp_type as "Update Type"
from
bugs b
left outer join
(select bp_comment_search as "Comment Body"
from bug_posts
group by bp_bug) bp on bp.bp_bug = b.bg_id
--inner join bug_posts bp on b.bg_id = bp.bp_bug
inner join statuses s on b.bg_status = s.st_id
inner join priorities p on b.bg_priority = p.pr_id
--where bp.bp_type = 'comment'
order by b.bg_id asc
我的SQL知識非常有限,但任何人都可以提供的幫助將不勝感激。謝謝!
你正在使用什麼樣的SQL(MySQL,Postgres,Oracle,MSSql)以及那個版本? –
我使用SQL Server 2008 – user1108721
我在下面的答案中添加了一個示例。將註釋放到列(而不是行)的部分 - >爲什麼要這樣做?你能給出一個期望輸出的例子嗎? –