gpt4 book ai didi

sql - 左连接,左表中没有重复行

转载 作者:行者123 更新时间:2023-12-03 06:22:43 25 4
gpt4 key购买 nike

请查看以下查询:

tbl_Contents

Content_Id  Content_Title    Content_Text
10002 New case Study New case Study
10003 New case Study New case Study
10004 New case Study New case Study
10005 New case Study New case Study
10006 New case Study New case Study
10007 New case Study New case Study
10008 New case Study New case Study
10009 New case Study New case Study
10010 SEO News Title SEO News Text
10011 SEO News Title SEO News Text
10012 Publish Contents SEO News Text

tbl_Media

Media_Id    Media_Title  Content_Id
1000 New case Study 10012
1001 SEO News Title 10010
1002 SEO News Title 10011
1003 Publish Contents 10012

查询

SELECT 
C.Content_ID,
C.Content_Title,
M.Media_Id

FROM tbl_Contents C
LEFT JOIN tbl_Media M ON M.Content_Id = C.Content_Id
ORDER BY C.Content_DatePublished ASC

结果

10002   New case Study  2014-03-31 13:39:29.280 NULL
10003 New case Study 2014-03-31 14:23:06.727 NULL
10004 New case Study 2014-03-31 14:25:53.143 NULL
10005 New case Study 2014-03-31 14:26:06.993 NULL
10006 New case Study 2014-03-31 14:30:18.153 NULL
10007 New case Study 2014-03-31 14:30:42.513 NULL
10008 New case Study 2014-03-31 14:31:56.830 NULL
10009 New case Study 2014-03-31 14:35:18.040 NULL
10010 SEO News Title 2014-03-31 15:22:15.983 1001
10011 SEO News Title 2014-03-31 15:22:30.333 1002
10012 Publish 2014-03-31 15:25:11.753 1000
10012 Publish 2014-03-31 15:25:11.753 1003

10012 来了两次...!

我的查询从 tbl_Contents 返回重复行(连接中的左表)

tbl_Contents 中的某些行在 tbl_Media 中具有超过 1 个关联行。即使 tbl_Media 中存在空值但没有重复记录,我也需要 tbl_Contents 中的所有行。

最佳答案

尝试 OUTER APPLY

SELECT 
C.Content_ID,
C.Content_Title,
C.Content_DatePublished,
M.Media_Id
FROM
tbl_Contents C
OUTER APPLY
(
SELECT TOP 1 *
FROM tbl_Media M
WHERE M.Content_Id = C.Content_Id
) m
ORDER BY
C.Content_DatePublished ASC

或者,您可以GROUP BY结果

SELECT 
C.Content_ID,
C.Content_Title,
C.Content_DatePublished,
M.Media_Id
FROM
tbl_Contents C
LEFT OUTER JOIN tbl_Media M ON M.Content_Id = C.Content_Id
GROUP BY
C.Content_ID,
C.Content_Title,
C.Content_DatePublished,
M.Media_Id
ORDER BY
C.Content_DatePublished ASC

OUTER APPLY 选择与左表中的每一行匹配的单行(或无)。

GROUP BY 执行整个联接,但随后折叠所提供列上的最终结果行。

关于sql - 左连接,左表中没有重复行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22769641/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com