您的位置:首页 > 编程语言 > PHP开发

php中mysql一条sql语句查询出所有符合条件的数据,该怎么写?

2016-11-21 21:12 886 查看
假如一个表里有个classid字段是类别的id,我想用一条sql语句查出classid=5的所有数据的id该怎么查呢?正常是要循环,放到数组里的吧




如图,我想查询classid=2的对应所有id,用一条sql语句

不知道你的a,b两表有没有关联,假定没有关联
select count(1)
from
(
select id
from a
where id>5
union all
select id
from b
where id>5
)

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 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关联)





内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐