[英]SQL: Get parent Join child where child type = 1 AND child type = 2
I have question in SQL (MySQL environment). 我在SQL(MySQL环境)中有疑问。 I have two tables:
我有两张桌子:
Airports
--------------------
id type city_id
1 2 1
2 3 1
3 4 2
City
----------
id name
1 Paris
2 Lyon
I want cities with airports whose type is 2 and 3. 我想要机场类型为2和3的城市。
I have try: 我试过了:
SELECT *
FROM city c INNER JOIN airports a ON a.city_id = c.id
WHERE a.type = 1 AND a.type = 2
But it does not work. 但它不起作用。
Any ideas ? 有任何想法吗 ?
If you are after the record paris which has two different types(1 and 2), try this: 如果你在记录巴黎之后有两种不同的类型(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
Result: 结果:
ID NAME
1 Paris
See result in SQL Fiddle . 在SQL Fiddle中查看结果。
To be more detailed: 更详细一点:
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
Result: 结果:
CID AID TYPE CITY_ID NAME
1 1 2 1 Paris
1 2 3 1 Paris
If you need cities where type 1 and 2 airports exist both then try to use this query: 如果您需要存在类型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
You can use a sub-query 您可以使用子查询
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";
And here you replace 1,2 (in the sub-query also) with the values you require 在这里,您可以使用所需的值替换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";
the above one returns correct data also 上面的一个也返回正确的数据
Could you try this? 你能试试吗?
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
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)))
Check this for sample output SQL FIDDLE 检查此示例输出SQL FIDDLE
You can use subquery for this.. Try this 您可以使用子查询。试试这个
Select Id,Name from City
where Id in(Select distinct CityId from Airports where Type in(2,3))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.