我在SQL(MySQL环境)中有疑问。我有两张桌子:
Airports
--------------------
id type city_id
1 2 1
2 3 1
3 4 2
City
----------
id name
1 Paris
2 Lyon
我想要机场类型为2和3的城市。
我试过了:
SELECT *
FROM city c INNER JOIN airports a ON a.city_id = c.id
WHERE a.type = 1 AND a.type = 2
但它不起作用。
有什么想法吗?
答案 0 :(得分:1)
如果您正在使用具有两种不同类型(1和2)的记录巴黎,请尝试:
SELECT c.*
FROM city c INNER JOIN
airports a ON a.city_id = c.id
WHERE a.type IN (2,3)
HAVING COUNT(DISTINCT a.type)>1
结果:
ID NAME
1 Paris
请参阅SQL Fiddle中的结果。
更详细:
SELECT c.id as CID,a.Id as AID,type,city_id,name
FROM city c INNER JOIN
airports a ON a.city_id=c.id LEFT JOIN
(SELECT c.id
FROM city c INNER JOIN
airports a ON a.city_id = c.id
WHERE a.type IN (2,3)
HAVING COUNT(DISTINCT a.type)>1) T ON T.id=c.id
WHERE T.id IS NOT NULL
结果:
CID AID TYPE CITY_ID NAME
1 1 2 1 Paris
1 2 3 1 Paris
小提琴Example。
答案 1 :(得分:1)
如果您需要存在类型1和2机场的城市,请尝试使用此查询:
SELECT * FROM CITY
JOIN
(
SELECT CITY_ID FROM Airports WHERE type in (1,2)
GROUP BY CITY_ID
HAVING COUNT(DISTINCT type) =2
) as A
ON City.ID=a.City_id
答案 2 :(得分:0)
您可以使用子查询
SELECT * FROM (
SELECT *, GROUP_CONCAT(a.type) as tp
FROM city c INNER JOIN airports a ON a.city_id = c.id
WHERE a.type IN (1,2)
) tmp WHERE tp = "1,2";
在这里你用你需要的值替换1,2(在子查询中)
SELECT * FROM (
SELECT c.id, c.name, GROUP_CONCAT(a.type) as tp
FROM city c JOIN airports a ON a.city_id = c.id
WHERE a.type IN (2,3)
) tmp WHERE tp = "2,3";
上述内容也会返回正确的数据
答案 3 :(得分:0)
你可以尝试一下吗?
SELECT *
FROM city c jINNER JOIN (
SELECT DISTINCT city_id
FROM airports t1 INNER JOIN airports t2
ON t1.city_id = t2.city_id
WHERE t1.type = 1 AND t2.type = 2
) a ON a.city_id = c.id
答案 4 :(得分:0)
select c.name from city c where exists
(select * from airport a where a.city_id=c.id and exists
(select * from airport a1 where a1.type=2 and a1.city_id=a.city_id and
exists(select * from airport a2 where a2.type=3 and a2.city_id=a1.city_id)))
检查此样本输出SQL FIDDLE
答案 5 :(得分:-1)
您可以使用子查询... 试试这个
Select Id,Name from City
where Id in(Select distinct CityId from Airports where Type in(2,3))