[英]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.