1. 程式人生 > 實用技巧 >SELECT 聯表查詢

SELECT 聯表查詢

匯入 World.sql

匯入一個 World 資料庫,點選下載,解壓即可

傳統連線

1. 連表查詢:世界上小於100人的城市在哪個國家?請列出城市名字,國家名字與人口數量

# 1.確認我要查哪些內容
國家名字  城市名字  城市人口數量   小於100人

# 2.確認在哪個表
country.name   city.name   city.population   

# 3.找出兩個表相關聯的欄位
city.countrycode   country.code

# 4.編寫語句
mysql> select country.name,city.name,city.population from country,city where city.countrycode=country.code and city.population < 100;
+----------+-----------+------------+
| name     | name      | population |
+----------+-----------+------------+
| Pitcairn | Adamstown |         42 |
+----------+-----------+------------+
1 row in set (0.01 sec)

2. 連表查詢:世界上小於100人的城市在哪個國家,是用什麼語言?請列出城市名字,國家名字與人口數量和國家語言

# 1.確認我要查哪些內容
國家名字  城市名字  城市人口數量   國家使用的語言   小於100人

# 2.確認在哪個表
country.name   city.name   city.population   countrylanguage.language

# 3.找出三個表相關聯的欄位
country.code   city.countrycode   countrylanguage.countrycode

# 4.寫sql語句
mysql> select country.name,city.name,city.population,countrylanguage.language from country,city,countrylanguage where country.code=city.countrycode and city.countrycode=countrylanguage.countrycode and city.population < 100;
+----------+-----------+------------+-------------+
| name     | name      | population | language    |
+----------+-----------+------------+-------------+
| Pitcairn | Adamstown |         42 | Pitcairnese |
+----------+-----------+------------+-------------+
1 row in set (0.04 sec)

自連線

# 自己查詢相同欄位,使用自連線,兩個關聯的表必須有相同欄位和相同資料
SELECT city.name,city.countrycode,countrylanguage.language,city.population
FROM  city NATURAL JOIN countrylanguage 
WHERE population > 1000000
ORDER BY population;

# 兩個表中沒有相同欄位不行,欄位相同值不同不行
SELECT country.name,city.name,city.population FROM city NATURAL JOIN country WHERE population < 100;

# 注意:
1.自連線必須有相同欄位和相同值
2.兩個表中的資料必須完全相同

內連線

外連線