0

我有一个 INNER JOIN 查询,它根据连接表中的值获取国家/地区名称:

SELECT DISTINCT countryName, countrySlug
FROM countries AS Country
INNER JOIN countries_networks AS n ON Country.id = n.country_id
AND n.network_id IN ( 6, 7, 8, 9, 14 ) 

但是,我现在需要select满足IN() 标准的那些,并且还必须包含网络 2

我显然不能只在 IN() 中添加 2,因为我需要 2 是强制性的,并且至少需要其中一个。

有人可以帮忙吗,我觉得它非常简单。

4

4 回答 4

1

试试这个:

SELECT DISTINCT 
  countryName, 
  countrySlug
FROM countries AS Country
INNER JOIN countries_networks AS n  ON Country.id   = n.country_id
                                   AND n.network_id IN (6, 7, 8, 9, 14) 
WHERE Country.id IN (SELECT id
                     FROM countries_networks 
                     WHERE network_id = 2
                       AND id IS NOT NULL);

这将确保任何选定的国家/地区都必须拥有network_id = 2.

于 2013-03-15T09:33:27.430 回答
1

首先,通过用子查询DISTINCT替换连接来删除。EXISTS然后您可以添加另一个子查询来处理额外的要求:

SELECT countryName, countrySlug
FROM countries AS c
WHERE EXISTS
      ( SELECT *
        FROM countries_networks AS n 
        WHERE c.id = n.country_id
          AND n.network_id IN ( 6, 7, 8, 9, 14 )
      )
  AND EXISTS
      ( SELECT *
        FROM countries_networks AS n 
        WHERE c.id = n.country_id
          AND n.network_id = 2
      ) ;
于 2013-03-15T09:38:18.263 回答
1

试试这个(双重加入?):

SELECT DISTINCT countryName, countrySlug, n.country_id, n2.country_id
FROM countries AS Country
INNER JOIN countries_networks AS n ON Country.id = n.country_id
AND n.network_id
IN ( 6, 7, 8, 9, 14 )
INNER JOIN countries_networks AS n2 ON Country.id = n2.country_id
AND n2.network_id = 2

注意:显示的n.country_id, n2.country_id值仅用于能够检查结果

于 2013-03-15T09:42:09.030 回答
-1

只需这样做:

SELECT DISTINCT countryName, countrySlug
FROM countries AS Country
INNER JOIN countries_networks AS n ON Country.id = n.country_id
AND n.network_id=2 And n.network_id IN (2, 6, 7, 8, 9, 14 )
于 2013-03-15T09:46:51.050 回答