数据库联合查找的sql语句
2016-10-12 19:37
218 查看
sql多表关联查询跟条件查询大同小异,主要是要知道表与表之前的关系很重要;
举例说明:(某数据库中有3张表分别为:userinfo,dep,sex)
userinfo(用户信息表)表中有三个字段分别为:user_di(用户编号),user_name(用户姓名),user_dep(用户部门) 。(关系说明:userinfo表中的user_dep字段和dep表中的dep_id字段为主外键关系,userinfo表中的user_sex字段和sex表中的sex_id字段为主外键关系)
dep(部门表)表中有两个字段分别为:dep_id(部门编号),dep_name(部门名称)。(主键说明:dep_id为主键)
sex(性别表)表中有两个字段分别为:sex_id(性别编号),sex_name(性别名称)。(主键说明:sex_id为主键)
一,两张表关键查询
1、在userinfo(用户信息表)中显示每一个用户属于哪一个部门。sql语句为:
select userinfo.user_di,userinfo.user_name,dep_name from userinfo,dep 4000 where userinfo.user_dep=dep.dep_id
2、在userinfo(用户信息表)中显示每一个用户的性别。sql语句为:
select userinfo.user_di,userinfo.user_name,sex.sex_name from userinfo,sex where userinfo.user_sex=sex.sex_id
二、多张表关键查询
最初查询出来的userinfo(用户信息表)表中部门和性别都是以数字显示出来的,如果要想在一张表中将部门和性别都用汉字显示出来,需要将三张表同时关联查询才能实现。
sql语句为:
select userinfo.user_di,userinfo.user_name,dep.dep_name,sex.sex_name from userinfo,dep,sex where userinfo.user_dep=dep.dep_id and userinfo.user_sex=sex.sex_id
(多个条件用and关联)
相关文章推荐
- SQL语句,在数据库的所有表里查找某一个字段值
- 【数据库SQL】查找特殊字符语句的使用案例
- 查找数据库中的topsql语句 (oracle)
- 2015.7.30 第十五课 sql(新建数据库、创建表、注释、查询语句、新增、更新、删除、联合查询)
- 查找oracle数据库系统里的bad sql语句的方法
- 利用SQL语句查找某数据库中所有存储过程包含的内容
- 利用SQL语句查找某数据库中所有存储过程包含的内容
- [mysql] 数据库查找时显示制定行的sql语句
- 15.6数据库(6):SQL语句进阶2:多表联合查询
- 在SQL SERVER中 用SQL语句查找数据库中含有字段的表名。
- sql语句怎么在一个数据库中查找拥有同一字段名的所有表
- 利用SQL语句查找某数据库中所有存储过程包含的内容
- 利用SQL语句查找某数据库中所有存储过程包含的内容(转)
- 查找数据库指定数据的数据表和字段名称SQL语句
- 查找数据库指定数据的数据表和字段名称SQL语句
- 跨服务器,跨数据库,多表联合查询 / 如何用sql语句来查询表中哪些记录是重复的
- 数据库基础学习3-T-SQL语句
- php 数据库可以查到数据的sql语句,在代码里为什么查不到数据
- 数据库复习总结(6)-SQL语句入门(脚本、命令)
- PHP相关系列 - PHP 数据库SQL语句安装组装类