![](/img/trans.png)
[英]SQL JOIN PARENT AND CHILD and GET count of PARENT and CHILD RECORDS
[英]SQL: Get parent Join child where child type = 1 AND child type = 2
我在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
但它不起作用。
有任何想法吗 ?
如果你在记录巴黎之后有两种不同的类型(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
小提琴示例 。
如果您需要存在类型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
您可以使用子查询
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";
上面的一个也返回正确的数据
你能试试吗?
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)))
检查此示例输出SQL FIDDLE
您可以使用子查询。试试这个
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.