1

这是我的国家/地区表:

id | name

这是我的语言表:

id | name

这是加入它们的 countryLanguages 表:

id | country_id | language_id

现在我想写一个查询来做出这样的选择

language_id | language_name

其中国家 id=3 的 countryLanguages 表中不存在语言。

例子:

countries:
1 | US
2 | UK
3 | CHINA

languages:
1 | chinese
2 | spanish
3 | english

countryLanguages:
1 | 1 | 3
2 | 1 | 2
3 | 2 | 3
4 | 3 | 1

它应该被退回:

2 | spanish
3 | english

因为在中国不说西班牙语和英语。

4

4 回答 4

1

您可以使用以下子查询来实现此目的:

# this is the outer select for every language not in the list returned from the inner query
SELECT * FROM languages WHERE languages.id NOT IN (
   # this is the inner select for every language spoken in country 3
   SELECT
        languages.id
   FROM 
        countries, countryLanguages, languages
   WHERE
        countries.id = countryLanguages.country_id AND
        languages.id = countryLanguages.language_id AND
        countries.id = 3
 );

请注意,子查询并不总是最快的方式来做某事,您通常可以想出一个 cleaver join 代替,但这应该可以满足您的需求。

于 2013-07-03T20:19:53.250 回答
0

Here is a solution using joins:

SELECT DISTINCT
  cl.language_id,
  l.name


FROM languages AS l

JOIN countryLanguages AS cl
  ON cl.language_id = l.id

JOIN countries AS c
  ON c.id = cl.country_id
 AND c.name != 'CHINA'

You could also use AND c.id != 3

SQL Fiddle

于 2013-07-03T20:28:49.390 回答
0
select * from languages where id not in (select language_id from countryLanguages where country_id=3)
于 2013-07-03T20:27:27.447 回答
0
SELECT DISTINCT cl.language_id, l.name
FROM languages AS l
JOIN countryLanguages AS cl ON cl.language_id = l.id
WHERE cl.country_id != 3
于 2013-07-03T20:42:04.120 回答