这是一个没有连接的版本,但使用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;