這裏是一個版本沒有加入,但使用EXISTS (SELECT ...)
它返回一個布爾值:
http://sqlfiddle.com/#!5/712bd/9
SELECT
Version.Vid, Version.VName, Version.IsActive,
EXISTS (
SELECT NULL FROM SubVersion WHERE SubVersion.Vid = Version.Vid
) AS SubVersionExists
FROM Version;
或者,如果你的SQL引擎不布爾值轉換爲0/1,就可以使用CASE
:
SELECT
Version.Vid, Version.VName, Version.IsActive,
CASE WHEN
EXISTS (SELECT NULL FROM SubVersion WHERE SubVersion.Vid = Version.Vid)
THEN 1 ELSE 0 END AS SubVersionExists
FROM Version
另一個版本LEFT JOIN
+ GROUP BY
,如果你不要使用COUNT()
:
SELECT
Version.Vid, Version.VName, Version.IsActive,
CASE WHEN SubVersionVids.Vid IS NOT NULL
THEN 1 ELSE 0 END AS SubVersionExists
FROM Version
LEFT JOIN (
SELECT SubVersion.Vid
FROM SubVersion
GROUP BY SubVersion.Vid
) AS SubVersionVids
ON SubVersionVids.Vid = Version.Vid;
或者你可以使用DISTINCT
代替GROUP BY
:
SELECT
Version.Vid, Version.VName, Version.IsActive,
CASE WHEN SubVersionVids.Vid IS NOT NULL
THEN 1 ELSE 0 END AS SubVersionExists
FROM Version
LEFT JOIN (
SELECT DISTINCT SubVersion.Vid
FROM SubVersion
) AS SubVersionVids
ON SubVersionVids.Vid = Version.Vid;
哇感謝您的快速回復它爲我工作 – sandeep
我希望你可以選擇一個:) – biziclop