首页 > 其他 > 详细

SELECT 联表查询

时间:2020-07-15 22:16:04      阅读:50      评论:0      收藏:0      [点我收藏+]

导入 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.两个表中的数据必须完全相同

内连接

外连接

SELECT 联表查询

原文:https://www.cnblogs.com/zzzwqh/p/13307235.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!