sql 备忘

**************************************
**** 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 by  b.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 a where a.deptid  in(select b.deptid from emp as b were a.deptid=b.deptid);

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

 ----删除重复记录(保留一条)------------------

----删除有重复的记录:

     delete from t_consumer

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值