可以有多个 Config_RecID,但我只想显示附加到 SR_Service_RecID 的第一个,或者当为 null 时显示 NULL。
SELECT s.SR_Service_RecID
, sc.Config_RecID
FROM SR_Service s
LEFT JOIN SR_Config sc
ON sc.SR_Service_RecID = s.SR_Service_RecID
WHERE (sc.Config_RecID =
(
SELECT TOP 1 sc.Config_RecID
FROM SR_Config sc
WHERE sc.SR_Service_RecID = s.SR_Service_RecID
)
OR sc.Config_RecID IS NULL)
有更好/更简洁的方法来做到这一点,还是我走在正确的道路上?
最佳答案
您可以将条件移至 ON
子句中:
SELECT s.SR_Service_RecID
, sc.Config_RecID
FROM SR_Service s
LEFT JOIN SR_Config sc
ON sc.SR_Service_RecID = s.SR_Service_RecID
AND sc.Config_RecID = (
SELECT TOP 1 Config_RecID
FROM SR_Config sc2
WHERE sc2.SR_Service_RecID = s.SR_Service_RecID
)
这样您就不需要额外检查 sc.Config_RecID IS NULL
关于sql - 只选择第一个结果...有更好的方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14188495/