ITeye博客

MySql sql 备忘

ileson · 2010-03-16 09:02 · Database · 数据库 · Markdown


MySql sql 查询备忘


一、外连接: 1、左外连接(把join左边表里的所有数据都查出来。然后把join 右边表中的符合条件的数据加在左边表的后面。。。。)

SELECT * FROM t_empl_info as a LEFT OUTER JOIN t_dept as b 
ON a.dept_no=b.dept_id

--通常情况下是:左边表是多方表。右边表是一方表 --三张表的左外连接

SELECT *
FROM A left join B
on A.a=B.a 
left join C on B.b = C.b;

二、嵌套查询 有两张一对多的表。 A 为一方表,B 为多方表。

select a.*,(select count(*) from B as b where 1=1 and a.x=b.x)as NUM--b 表中外键是a 表主键。
from A as a where 1=1

----例:混合性查询--- ---------下例为:查出主表下其中一个,共有多少明细。(相当于某个部门共有多少名员工) 1、

select a.*,(select count(*) from B as b where a.id=b.id) as NUM
from A as a left join C as c on a.x=c.x
where 1=1 and qc_stat not in(1)

2、前提:a 部门表 b 员工表 a表字段( id --部门编号 departmentName-部门名称 ) b表字段( id--部门编号 employee- 员工名称 )

问题:如何一条sql语句查询出每个部门共有多少人

select count(b.id)as employeecount,a.departmentName from a
left join b on a.id=b.id
group byb.id,a.departmentName

MySql sql other备忘


1、新增明细时。主表总数加一

update t_prod_list set num=num+1 where id =?

2、得到最大值

select max(ID) AS ID ,a.PROD_NO from t_prod_list_details as a GROUP by a.id desc

---group by 功能:分组查询。如下例: ID 名称 仓库 数量 01 西瓜 一号 10 02 西瓜 二号 30 03 大米 一号 30 04 苹果 一号 40 05 苹果 二号 45 06 苹果 三号 5

Select name,Sum(price) From 表 Group By name

以上SQL将返回各种商品的总数量,而不管是哪个仓库的..

结果:

西瓜,40 大米,30 苹果,90

现有两张表: 部门表dept(deptid,deptname) 员工表emp(empid,deptid,empname) 问题:查有员工的部门? 1、

select a.* from dept as awhere a.deptid in(select b.deptid from emp as b were a.deptid=b.deptid);

2、

select a.* from dept as awhere (select count(*) from emp as b were a.deptid=b.deptid)>0

--查询重复记录


select distinct t1.id,t1.usercode from t_consumer t1, t_consumer t2 where t1.id != t2.id and t1.usercode = t2.usercode
select * from t_consumer
where cardnum in(select distinct cardnum from t_consumer group by cardnum having count(cardnum)>1)

----删除重复记录(保留一条)------------------ http://www.cnblogs.com/congcong/archive/2008/11/07/1328834.html ----删除有重复的记录:

delete from t_consumer
where cardnum in(select distinct cardnum from t_consumer group by cardnum having count(cardnum)>1)

四、MySql 内置函数使用。 1、拼接字符串

select concat(xiaoqubianhao,'-',louhao ,'-',danyuan,'-',menpaihao) from t_userinfo

2、----字段补零----------

select right(concat('0000',id),5) as id   from table

1 显示为 00001 2 显示为 00002 999 显示为 00999 1000 显示为 01000

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。