我在SQL Server中有一个查询返回一个Reports列表,它必须返回一个表示位置的字符串,或者一个表示它引用的存储的字符串。
问题是我的查询只返回引用商店ID的报表,而不是返回所有报表和相关位置信息。我确信它是一个愚蠢的语法问题,但我暂时还没有完成数据库工作,似乎无法解决它。我已经尝试了几种不同的方法来实现这一点,但它只是拒绝。
SELECT rep.rep_id AS "RepId",
Isnull(rep.rep_status, 'C') AS "RepStatus",
Isnull(( loc.location_street + ' ' + loc.location_city ), store.Description) AS "Location",
rep.date_reported AS "DateReported",
rep.reported_by AS "ReportedBy"
FROM Report rep
JOIN Report_Location reploc
ON reploc.rep_id = rep.rep_id
JOIN Location loc
ON loc.location_id = reploc.location_id
LEFT JOIN Store store
ON store.StoreID = loc.store_id;
我尝试删除左连接,只添加一个loc.store_id = store.StoreID或loc.store_id IS NULL。都没有奏效。在此先感谢您的帮助。
答案 0 :(得分:3)
您需要使用LEFT OUTER JOIN
代替Inner Join
SELECT rep.rep_id AS "RepId",
Isnull(rep.rep_status, 'C') AS "RepStatus",
Isnull(( loc.location_street + ' ' + loc.location_city ), store.Description) AS "Location",
rep.date_reported AS "DateReported",
rep.reported_by AS "ReportedBy"
FROM Report rep
LEFT JOIN Report_Location reploc
ON reploc.rep_id = rep.rep_id
LEFT JOIN Location loc
ON loc.location_id = reploc.location_id
LEFT JOIN Store store
ON store.StoreID = loc.store_id;
答案 1 :(得分:1)
使用左外连接实现:
SELECT rep.rep_id AS RepId, ISNULL(rep.rep_status, 'C') AS RepStatus, ISNULL(loc.location_street + ' ' + loc.location_city, store.Description) AS Location,
rep.date_reported AS DateReported, rep.reported_by AS ReportedBy
FROM Report AS rep LEFT OUTER JOIN
Report_Location AS reploc ON reploc.rep_id = rep.rep_id LEFT OUTER JOIN
Location AS loc ON loc.location_id = reploc.location_id LEFT OUTER JOIN
Store AS store ON store.StoreID = loc.store_id