1. 单表查询:
表名:user_information
id | name | address |
1 | 张三 | 山西临汾 |
2 | 李四 | 山西运城 |
3 | 王二 | 河南郑州 |
(1)查询id为2的用户信息:(这里的ui是user_information表的别名,*代表所有字段)
select ui.* from user_information ui where ui.id = 1;
(2)查询家庭住址是山西运城的用户信息:(如果where后面的字段为字符串,用单引号,否则不需要)
select ui.* from user_information ui where ui.address = '山西运城';
(3)查询家庭住址包括山西运城的用户信息:(如果where后面是模糊查询,前后加百分号)
select ui.* from user_information ui where ui.address like '%山西运城%';
(4)查询id为2的用户姓名:(查询具体字段只需要在别名后加字段名)
select ui.name from user_information ui where ui.id = 1;
2. 多表查询:
表1名:user_information
id | name | address |
1 | 张三 | 山西临汾 |
2 | 李四 | 山西运城 |
3 | 王二 | 河南郑州 |
表2名:user_job
id | job |
1 | 老师 |
2 | 学生 |
4 | 医生 |
(1)内联查询(inner join……on……)
查询用户的所有信息:
select * from user_information ui inner join user_job uj on ui.id = uj.id
id | name | address | id | job |
1 | 张三 | 山西临汾 | 1 | 老师 |
2 | 李四 | 山西运城 | 2 | 学生 |
(2)左联查询(left join……on……)
查询用户的所有信息:
select * from user_information ui left join user_job uj on ui.id = uj.id
id | name | address | id | job |
1 | 张三 | 山西临汾 | 1 | 老师 |
2 | 李四 | 山西运城 | 2 | 学生 |
3 | 王二 | 河南郑州 | null | null |
(3)右联查询(right join……on……)
查询用户的所有信息:
select * from user_information ui right join user_job uj on ui.id = uj.id
id | name | address | id | job |
1 | 张三 | 山西临汾 | 1 | 老师 |
2 | 李四 | 山西运城 | 2 | 学生 |
null | null | null | 4 | 医生 |