SELECT CountryCode, Name AS Country, Language
FROM Country INNER JOIN CountryLanguage
ON Country.Code = CountryLanguage.CountryCode
WHERE Language = 'German'
ORDER BY Country;

How would you use EXISTS and a subquery with this SELECT Statement?

有帮助吗?

解决方案

This should yield the same result and uses EXISTS:

select countrycode, name as country, language
  from country y
 where exists (select 'fish'
          from countrylanguage x
         where x.countrycode = y.code
           and x.language = 'German')
 order by country;

With an EXISTS subquery, if the subquery returns anything, the condition passes, and if it returns no rows, it fails, it doesn't matter what you put in the select statement (notice I typed in 'fish'). But that subquery will still return a row in any situation where the country has a row on countrylanguage where the language is german, and so for the rows of country that are applicable to you, the condition passes, and so it filters the same way.

其他提示

Thanks for all the tips. I was able to patch together a solution with EXISTS and a subquery that yields the same results as my original SELECT Statement.

SELECT CountryCode, Name AS Country, Language
FROM CountryLanguage AS X INNER JOIN Country AS Y
ON X.CountryCode = Y.Code
WHERE EXISTS
    (
    SELECT 'German'
    FROM CountryLanguage AS X
    WHERE X.CountryCode = Y.Code
    AND X.Language = 'German'
    )
AND X.Language = 'German'
ORDER BY Country;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top