我写了以下查询:
SELECT
CAN.Cycle
, CAN.FECCandID
, CAN.CID
, CAN.FirstLastP
, CAN.Party
, CAN.DistIDRunFor
, CAN.DistIDCurr
, CAN.CurrCand
, CAN.CycleCand
, CAN.CRPICO
, CAN.RecipCode
, CAN.NoPacs
FROM Cands16 AS CAN
JOIN MercerRobert_Indivs AS MER
ON CAN.CID = MER.RecipID
我的目标是返回来自Cands16的每一行,其中CID = RecipID。这就是结果:
虽然MER表确实具有RecipID具有相同值的多个事件的行,但Cands16表中的每个CID事件都是唯一的。我不希望我的查询产生这些重复的行。所以我该怎么做?我正在使用SQL Server 2016 Management Studio。
答案 0 :(得分:3)
看到你不使用MER的任何列,你似乎只想知道MER中是否存在这样的id。所以最简单的方法是删除连接:
select
CAN.Cycle
, CAN.FECCandID
, CAN.CID
, CAN.FirstLastP
, CAN.Party
, CAN.DistIDRunFor
, CAN.DistIDCurr
, CAN.CurrCand
, CAN.CycleCand
, CAN.CRPICO
, CAN.RecipCode
, CAN.NoPacs
from Cands16 CAN
where exists (
select *
from MercerRobert_Indivs MER
where CAN.CID = MER.RecipID
) ;
答案 1 :(得分:1)
您的示例SQL使用简单连接。
SQL Server(Transact-SQL)JOINS用于从多个表中检索数据。只要在SQL语句中连接两个或多个表,就会执行SQL Server JOIN。
有4种不同类型的SQL Server连接:
有关您可以使用的不同联接的详细信息和说明,请参阅this link。
答案 2 :(得分:1)
尝试:
SELECT
CAN.Cycle
, CAN.FECCandID
, CAN.CID
, CAN.FirstLastP
, CAN.Party
, CAN.DistIDRunFor
, CAN.DistIDCurr
, CAN.CurrCand
, CAN.CycleCand
, CAN.CRPICO
, CAN.RecipCode
, CAN.NoPacs
FROM Cands16 AS CAN
-- the same RecipID can occur several times in MercerRobert_Indivs
-- so make sure this is not the case before joining ...
JOIN (SELECT DISTINCT RecipID FROM MercerRobert_Indivs) AS MER
ON CAN.CID = MER.RecipID