获取表中包含两个变量的所有行

时间:2014-07-01 14:07:49

标签: mysql sql

我需要从包含两个城市ID的表中获取所有公司ID(让我们说7333和10906)但是id并不像我那样工作。

这是我的表:

enter image description here

这是我的代码

   SELECT `company_id` as id 
   FROM `logistics_companies_destinations` 
   WHERE `city_id`= 7333 and `city_id` = 10906

3 个答案:

答案 0 :(得分:4)

MySQL没有INTERSECT关键字,但实现此目的的一种方法是:

   SELECT `company_id` as id 
   FROM `logistics_companies_destinations` 
   WHERE 
        `city_id` = 10906
        and `company_id` IN (SELECT `company_id` as id 
                             FROM `logistics_companies_destinations` 
                             WHERE `city_id`= 7333)

[另一种方式(如另一张海报的注释)是两次加入表格并将过滤条件应用于每个连接]。

答案 1 :(得分:1)

您也可以使用INNER JOIN对表本身进行解决,加入相同的company_id并要求两个city_ids都存在:

SELECT
        `lcd1`.`company_id` AS id 
   FROM `logistics_companies_destinations` AS lcd1
   INNER JOIN `logistics_companies_destinations` AS lcd2
   WHERE `lcd1`.`city_id`= 7333 AND `lcd2`.`city_id` = 10906

对不起,我通常也对这样愚蠢的缩写表名不屑一顾,但没有提出更好的别名;)

答案 2 :(得分:-1)

我相信你的问题是“和”。如果city_id等于“7333”和“10906”,您正在寻找company_id。使用或它应该工作。