当前位置: 澳门新濠3559 > 数据库 > 正文

希望指正,二 子查询和连接

时间:2019-10-07 09:08来源:数据库
修改语句: 子查询与连接 数据准备 SQL难题求解!SQL难题求解! --SELECT * FROM sale_detail sd WHERE split_count IS NOT NULL update A set WZCount=ISNULL(WZCount,0) (select SUM(WZCount) fromT_PM_OutStock_SUB where Materi

修改语句:

子查询与连接
数据准备

SQL难题求解!SQL难题求解!
图片 1

--SELECT * FROM sale_detail sd WHERE split_count IS NOT NULL

update A set WZCount=ISNULL(WZCount,0) (select SUM(WZCount) from T_PM_OutStock_SUB where MaterialID =A.MaterialID and _MainID='{_AutoID}') from T_PM_MaterialStock A,T_PM_OutStock_SUB

一、复习:
MYSQL记录操作:写操作(insert、update、delete)和读操作select
二 子查询和连接
tdb_goods表结构
good_id---商品ID good_name---商品名称 good_eate 商品类型
brand_name 品牌名称 goods_price 商品价格 is_show 是否上架
is_saleoff 是否售空
虽然MySQL配置了客户端和服务器的编码格式均为utf8编码,但在已建的数据表插入记录时,MySQL仍然不识别中文,会抛出Incorrect String Value异常。
该问题的解决办法即:

SELECT a.PNO ,
a.Uname ,
isnull(a.pronum - b.SPCnumber,0) AS sjxsnum
FROM ( SELECT TOP 100 PERCENT
cong.PNO ,
zhu.Uname ,
SUM(cong.BenCiNum) pronum
FROM dbo.TBFaHuo zhu
RIGHT JOIN ( SELECT PNO ,
BenCiNum ,
FhId
FROM dbo.TBFaHuoDetail c
) cong ON zhu.FhId = cong.fhId
WHERE cong.PNO = 'kl008'
GROUP BY zhu.Uname ,
cong.PNO
ORDER BY ProNum DESC
) a
LEFT JOIN
( SELECT TOP 100 PERCENT
ddmx.PNO ,
dd.UName ,
SUM(thmx.SPCnumber) SPCnumber
FROM dbo.TBSalesReturnPro thmx
INNER JOIN ( SELECT id ,
pno ,
oid
FROM dbo.TBOrderPro mx
) ddmx ON ddmx.ID = thmx.OPID
INNER JOIN ( SELECT OID ,
UName
FROM TBOrder
) dd ON dd.OID = ddmx.oid
WHERE ddmx.PNO = 'kl008'
GROUP BY ddmx.PNO ,
dd.UName
) b ON b.UName = a.Uname

--SELECT * FROM sale_detail sd WHERE split_amount IS NULL

系统报错:

  1. 在插入记录之前,通过SET NAMES gbk;设置客户端的编码格式,即敲入的是什么编码,客户端会自动将插入命令转换成utf8编码
  2. 当然在查询记录之前,也需要通过SET NAMES gbk;设置客户端数据显示的编码,否则会出现乱码
  3. SET NAMES gbk;只会影响客户端显示数据的编码,对源数据不会有任何影响
    子查询
    1.子查询是指出现在【其他SQL语句内】的SELECT子句
    eg:
    SELECT * FROM t1 WHERE column1 = (SELECT column1 FROM t2);
    其中,SELECT * FROM t1 ...称为Outer Query[外查询](或者Outer Statement)
    SELECT column1 FROM t2 称为Sub Query[子查询]
    ps:Outer Query[外查询]并不单单指SELECT等查询语句,而是所有的SQL语句,当一个SQL语句包含了子查询,则包含子查询的语句就叫外查询
    2子查询的条件:
    1)始终出现在圆括号内;
    2)可以包含多个关键字或者条件;如 distinct、group by、order by、limit、函数等 (改为大写)
    3)子查询的外查询可以是:【SELECT,INSERT,UPDATE,SET或DO】。SQL语句的统称
    3.子查询的返回值
    子查询可以返回标量、一行、一列或子查询

附上错误的sql语句,希望指正!

SET NOCOUNT OFF

聚合不应出现在 UPDATE 语句的集合列表中

使用比较运算符的子查询
使用比较运算符
=、>、<、>=、<=、<>、!=、<=>
语法结构
operand comparison_operator subquery

WHILE 1=1

问题:

SELECT AVG (col_name) FROM tbl_name;
查找数据表中某列的平均值

BEGIN

修改语句中不能出现聚合函数这一类的

SELECT AVG(goods_price) FROM tdb_goods; //AVG函数代表求其平均值//
SELECT ROUND(AVG(goods_price),2) FROM tdb_goods; //round(@,#)代表对@数字进行四舍五入,且保留小数点后#位输出//
SELECT goods_id,goods_name,goods_price FROM tdb_goods WHERE goods_price>=5391.30; //输出价格大于5391.30的id、name、price//
综合起来运用子查询时:
SELECT goods_id,goods_name,goods_price FROM tdb_goods WHERE goods_price>=(SELECT ROUND(AVG(goods_price),2) FROM tdb_goods); //查找价格大于平均值的商品//
SELECT goods_price FROM tdb_price WHERE goods_cate='超级本'G; //检索分类为”超极本”的商品价格且一网格显示//
对于ANY、SOME、ALL的用法各有不同:(ANY和SOME用法相同)
SELECT goods_id,goods_name,goods_price FROM tdb_goods WHERE goods_price>=ANY (SELECT goods_price FROM tdb_goods WHERE goods_cate='超级本');

WITH cte AS

解决问题:

SELECT goods_id,goods_name,goods_price FROM tdb_goods WHERE goods_price>=ALL (SELECT goods_price FROM tdb_goods WHERE goods_cate='超级本');

(

那就把聚合函数放到select 查询与查出来当成一个数据表   再用数据表和原先的数据表匹配 进行添加

SELECT goods_id,goods_name,goods_price FROM tdb_goods WHERE goods_price>=SOME (SELECT goods_price FROM tdb_goods WHERE goods_cate='超级本');
第二种子查询---[NOT] IN
in 相当于 = any
not in 相当于 != all 或者<>all ——不等于、不包含
子查询----exists not exists ——用得比较少
子查询返回任何行 exists 返回 true 反之 返回 false
-- = ANY 或 = SOME 等价于 IN
EG:SELECT goods_id,goods_name,goods_price FROM tdb_goods WHERE goods_price !=ALL (SELECT goods_price FROM tdb_goods WHERE goods_cate='超级本' )//得到19个记录(22-3)
SELECT goods_id,goods_name,goods_price FROM tdb_goods WHERE goods_price IN (SELECT goods_price FROM tdb_goods WHERE goods_cate = '超级本')
//得到3个记录
第三种子查询.使用 [NOT] EXISTS 的子查询(较少用)
子查询的总结
1.子查询是指在另一个查询语句中的SELECT子句。
例句:
SELECT * FROM t1 WHERE column1 = (SELECT column1 FROM t2);
其中,SELECT * FROM t1 ...称为Outer Query[外查询](或者Outer Statement),
SELECT column1 FROM t2 称为Sub Query[子查询]。
所以,我们说子查询是嵌套在外查询内部。而事实上它有可能在子查询内部再嵌套子查询。
子查询必须出现在圆括号之间。
行级子查询
SELECT * FROM t1 WHERE (col1,col2) = (SELECT col3, col4 FROM t2 WHERE id = 10);
SELECT * FROM t1 WHERE ROW(col1,col2) = (SELECT col3, col4 FROM t2 WHERE id = 10);
行级子查询的返回结果最多为一行。
优化子查询
-- 创建数据表
CREATE TABLE IF NOT EXISTS tdb_goods(
goods_id SMALLINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
goods_name VARCHAR(150) NOT NULL,
goods_cate VARCHAR(40) NOT NULL,
brand_name VARCHAR(40) NOT NULL,
goods_price DECIMAL(15,3) UNSIGNED NOT NULL DEFAULT 0,
is_show BOOLEAN NOT NULL DEFAULT 1,
is_saleoff BOOLEAN NOT NULL DEFAULT 0
);

SELECT TOP (100000) * FROM dbo.sale_detail WHERE split_count IS NULL OR split_amount IS NULL

修改之后;

-- 写入记录

 

UPDATE T_PM_MaterialStock
SET WZCount = WZCount TB.ALLCount
FROM (SELECT
b.MaterialID,SUM(b.Count) AS ALLCount
FROM
T_PM_MaterialStock a
INNER JOIN
T_PM_OutStock_SUB b
ON a.MaterialID = b.MaterialID
WHERE b._MainID='{_AutoID}'
GROUP BY
b.MaterialID
) AS TB
WHERE
T_PM_MaterialStock.MaterialID = TB.MaterialID

INSERT tdb_goods (goods_name,goods_cate,brand_name,goods_price,is_show,is_saleoff) VALUES('R510VC 15.6英寸笔记本','笔记本','华硕','3399',DEFAULT,DEFAULT);

)

正常示例:

INSERT tdb_goods (goods_name,goods_cate,brand_name,goods_price,is_show,is_saleoff) VALUES('Y400N 14.0英寸笔记本电脑','笔记本','联想','4899',DEFAULT,DEFAULT);

UPDATE ssd SET ssd.split_count=tt.split_count,ssd.split_amount=tt.split_amount

UPDATE    库存表2
SET              库存数量 = TB.剩余数量
FROM  (SELECT 
      入库表.条形码,SUM(入库表.剩余数量) AS 剩余数量
      FROM  
      库存表2 
      INNER JOIN
      入库表 
      ON 库存表2.条形码 = 入库表.条形码 
      GROUP BY
      入库表.条形码
      ) AS TB 
      WHERE
      库存表2.条形码 = TB.条形码
另外一个语句写的例子:

INSERT tdb_goods (goods_name,goods_cate,brand_name,goods_price,is_show,is_saleoff) VALUES('G150TH 15.6英寸游戏本','游戏本','雷神','8499',DEFAULT,DEFAULT);

FROM cte ssd

UPDATE T_PM_MaterialEntry_SUB
SET Surplus = ISNULL(Surplus,0) TB.ALLCount
FROM (SELECT
b.SourceNumID,SUM(b.Count) AS ALLCount
FROM
T_PM_MaterialEntry_SUB a
INNER JOIN
T_PM_OutStock_SUB b
ON a._AutoID = b.SourceNumID
WHERE b._MainID='{_AutoID}'
GROUP BY
b.SourceNumID
) AS TB
WHERE
T_PM_MaterialEntry_SUB._AutoID = TB.SourceNumID

INSERT tdb_goods (goods_name,goods_cate,brand_name,goods_price,is_show,is_saleoff) VALUES('X550CC 15.6英寸笔记本','笔记本','华硕','2799',DEFAULT,DEFAULT);

JOIN (

INSERT tdb_goods (goods_name,goods_cate,brand_name,goods_price,is_show,is_saleoff) VALUES('X240(20ALA0EYCD) 12.5英寸超极本','超级本','联想','4999',DEFAULT,DEFAULT);

SELECT a.rid,SUM(ISNULL(a.split_units,0)) AS split_count,SUM(ISNULL(a.split_rmb,0)) AS split_amount

INSERT tdb_goods (goods_name,goods_cate,brand_name,goods_price,is_show,is_saleoff) VALUES('U330P 13.3英寸超极本','超级本','联想','4299',DEFAULT,DEFAULT);

FROM (

INSERT tdb_goods (goods_name,goods_cate,brand_name,goods_price,is_show,is_saleoff) VALUES('SVP13226SCB 13.3英寸触控超极本','超级本','索尼','7999',DEFAULT,DEFAULT);

SELECT sd.rid, SUM(( CASE WHEN pk.count IS NULL THEN 1 ELSE pk.count END ) * sd.count) AS split_units,

INSERT tdb_goods (goods_name,goods_cate,brand_name,goods_price,is_show,is_saleoff) VALUES('iPad mini MD531CH/A 7.9英寸平板电脑','平板电脑','苹果','1998',DEFAULT,DEFAULT);

SUM(CASE WHEN pk.price IS NULL THEN sd.amount ELSE pk.price * pk.count * sd.count END ) AS split_rmb

INSERT tdb_goods (goods_name,goods_cate,brand_name,goods_price,is_show,is_saleoff) VALUES('iPad Air MD788CH/A 9.7英寸平板电脑 (16G WiFi版)','平板电脑','苹果','3388',DEFAULT,DEFAULT);

FROM cte sd WITH(NOLOCK)

INSERT tdb_goods (goods_name,goods_cate,brand_name,goods_price,is_show,is_saleoff) VALUES(' iPad mini ME279CH/A 配备 Retina 显示屏 7.9英寸平板电脑 (16G WiFi版)','平板电脑','苹果','2788',DEFAULT,DEFAULT);

LEFT JOIN product p WITH(NOLOCK) ON p.product_id = sd.product_id

INSERT tdb_goods (goods_name,goods_cate,brand_name,goods_price,is_show,is_saleoff) VALUES('IdeaCentre C340 20英寸一体电脑 ','台式机','联想','3499',DEFAULT,DEFAULT);

LEFT JOIN product_kit pk WITH(NOLOCK) ON pk.kit_id = p.product_id

INSERT tdb_goods (goods_name,goods_cate,brand_name,goods_price,is_show,is_saleoff) VALUES('Vostro 3800-R1206 台式电脑','台式机','戴尔','2899',DEFAULT,DEFAULT);

AND pk.status = 0

INSERT tdb_goods (goods_name,goods_cate,brand_name,goods_price,is_show,is_saleoff) VALUES('iMac ME086CH/A 21.5英寸一体电脑','台式机','苹果','9188',DEFAULT,DEFAULT);

AND sd.sale_date >= pk.start_date

INSERT tdb_goods (goods_name,goods_cate,brand_name,goods_price,is_show,is_saleoff) VALUES('AT7-7414LP 台式电脑 (i5-3450四核 4G 500G 2G独显 DVD 键鼠 Linux )','台式机','宏碁','3699',DEFAULT,DEFAULT);

AND sd.sale_date <= pk.end_date

INSERT tdb_goods (goods_name,goods_cate,brand_name,goods_price,is_show,is_saleoff) VALUES('Z220SFF F4F06PA工作站','服务器/工作站','惠普','4288',DEFAULT,DEFAULT);

WHERE sd.status = 0

INSERT tdb_goods (goods_name,goods_cate,brand_name,goods_price,is_show,is_saleoff) VALUES('PowerEdge T110 II服务器','服务器/工作站','戴尔','5388',DEFAULT,DEFAULT);

AND p.status <> 1

INSERT tdb_goods (goods_name,goods_cate,brand_name,goods_price,is_show,is_saleoff) VALUES('Mac Pro MD878CH/A 专业级台式电脑','服务器/工作站','苹果','28888',DEFAULT,DEFAULT);

AND p.ispromotion = 0

INSERT tdb_goods (goods_name,goods_cate,brand_name,goods_price,is_show,is_saleoff) VALUES(' HMZ-T3W 头戴显示设备','笔记本配件','索尼','6999',DEFAULT,DEFAULT);

GROUP BY sd.rid

INSERT tdb_goods (goods_name,goods_cate,brand_name,goods_price,is_show,is_saleoff) VALUES('商务双肩背包','笔记本配件','索尼','99',DEFAULT,DEFAULT);

) a

INSERT tdb_goods (goods_name,goods_cate,brand_name,goods_price,is_show,is_saleoff) VALUES('X3250 M4机架式服务器 2583i14','服务器/工作站','IBM','6888',DEFAULT,DEFAULT);

GROUP BY a.rid

INSERT tdb_goods (goods_name,goods_cate,brand_name,goods_price,is_show,is_saleoff) VALUES('玄龙精英版 笔记本散热器','笔记本配件','九州风神','',DEFAULT,DEFAULT);

) tt ON ssd.rid = tt.rid

INSERT tdb_goods (goods_name,goods_cate,brand_name,goods_price,is_show,is_saleoff) VALUES(' HMZ-T3W 头戴显示设备','笔记本配件','索尼','6999',DEFAULT,DEFAULT);

 IF @@ROWCOUNT<100000 BREAK;

INSERT tdb_goods (goods_name,goods_cate,brand_name,goods_price,is_show,is_saleoff) VALUES('商务双肩背包','笔记本配件','索尼','99',DEFAULT,DEFAULT);

end

-- 求所有电脑产品的平均价格,并且保留两位小数,AVG,MAX,MIN、COUNT、SUM为聚合函数
SELECT ROUND(AVG(goods_price),2) AS avg_price FROM tdb_goods;
-- 查询所有价格大于平均价格的商品,并且按价格降序排序
SELECT goods_id,goods_name,goods_price FROM tdb_goods WHERE goods_price > 5845.10 ORDER BY goods_price DESC;
-- 使用子查询来实现
SELECT goods_id,goods_name,goods_price FROM tdb_goods
WHERE goods_price > (SELECT ROUND(AVG(goods_price),2) AS avg_price FROM tdb_goods)
ORDER BY goods_price DESC;
-- 查询类型为“超记本”的商品价格
SELECT goods_price FROM tdb_goods WHERE goods_cate = '超级本';
-- 查询价格大于或等于"超级本"价格的商品,并且按价格降序排列
SELECT goods_id,goods_name,goods_price FROM tdb_goods
WHERE goods_price = ANY(SELECT goods_price FROM tdb_goods WHERE goods_cate = '超级本')
ORDER BY goods_price DESC;
-- = ANY 或 = SOME 等价于 IN
SELECT goods_id,goods_name,goods_price FROM tdb_goods
WHERE goods_price IN (SELECT goods_price FROM tdb_goods WHERE goods_cate = '超级本')
ORDER BY goods_price DESC;
-- 创建“商品分类”表
CREATE TABLE IF NOT EXISTS tdb_goods_cates(
cate_id SMALLINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
cate_name VARCHAR(40)
);
-- 查询tdb_goods表的所有记录,并且按"类别"分组
SELECT goods_cate FROM tdb_goods GROUP BY goods_cate;
-- 将分组结果写入到tdb_goods_cates数据表
INSERT tdb_goods_cates (cate_name) SELECT goods_cate FROM tdb_goods GROUP BY goods_cate;
-- 通过tdb_goods_cates数据表来更新tdb_goods表
UPDATE tdb_goods INNER JOIN tdb_goods_cates ON goods_cate = cate_name
SET goods_cate = cate_id ;
-- 通过CREATE...SELECT来创建数据表并且同时写入记录
-- SELECT brand_name FROM tdb_goods GROUP BY brand_name;
CREATE TABLE tdb_goods_brands (
brand_id SMALLINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
brand_name VARCHAR(40) NOT NULL
) SELECT brand_name FROM tdb_goods GROUP BY brand_name;
-- 通过tdb_goods_brands数据表来更新tdb_goods数据表(错误)
UPDATE tdb_goods INNER JOIN tdb_goods_brands ON brand_name = brand_name
SET brand_name = brand_id;
-- Column 'brand_name' in field list is ambigous
-- 正确
UPDATE tdb_goods AS g INNER JOIN tdb_goods_brands AS b ON g.brand_name = b.brand_name
SET g.brand_name = b.brand_id;
-- 查看tdb_goods的数据表结构
DESC tdb_goods;
-- 通过ALTER TABLE语句修改数据表结构
ALTER TABLE tdb_goods
CHANGE goods_cate cate_id SMALLINT UNSIGNED NOT NULL,
CHANGE brand_name brand_id SMALLINT UNSIGNED NOT NULL;
-- 分别在tdb_goods_cates和tdb_goods_brands表插入记录
INSERT tdb_goods_cates(cate_name) VALUES('路由器'),('交换机'),('网卡');
INSERT tdb_goods_brands(brand_name) VALUES('海尔'),('清华同方'),('神舟');
-- 在tdb_goods数据表写入任意记录
INSERT tdb_goods(goods_name,cate_id,brand_id,goods_price) VALUES(' LaserJet Pro P1606dn 黑白激光打印机','12','4','1849');
-- 查询所有商品的详细信息(通过内连接实现)
SELECT goods_id,goods_name,cate_name,brand_name,goods_price FROM tdb_goods AS g
INNER JOIN tdb_goods_cates AS c ON g.cate_id = c.cate_id
INNER JOIN tdb_goods_brands AS b ON g.brand_id = b.brand_idG;
-- 查询所有商品的详细信息(通过左外连接实现)
SELECT goods_id,goods_name,cate_name,brand_name,goods_price FROM tdb_goods AS g
LEFT JOIN tdb_goods_cates AS c ON g.cate_id = c.cate_id
LEFT JOIN tdb_goods_brands AS b ON g.brand_id = b.brand_idG;
-- 查询所有商品的详细信息(通过右外连接实现)
SELECT goods_id,goods_name,cate_name,brand_name,goods_price FROM tdb_goods AS g
RIGHT JOIN tdb_goods_cates AS c ON g.cate_id = c.cate_id
RIGHT JOIN tdb_goods_brands AS b ON g.brand_id = b.brand_idG;
-- 无限分类的数据表设计
CREATE TABLE tdb_goods_types(
type_id SMALLINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
type_name VARCHAR(20) NOT NULL,
parent_id SMALLINT UNSIGNED NOT NULL DEFAULT 0
);
INSERT tdb_goods_types(type_name,parent_id) VALUES('家用电器',DEFAULT);
INSERT tdb_goods_types(type_name,parent_id) VALUES('电脑、办公',DEFAULT);
INSERT tdb_goods_types(type_name,parent_id) VALUES('大家电',1);
INSERT tdb_goods_types(type_name,parent_id) VALUES('生活电器',1);
INSERT tdb_goods_types(type_name,parent_id) VALUES('平板电视',3);
INSERT tdb_goods_types(type_name,parent_id) VALUES('空调',3);
INSERT tdb_goods_types(type_name,parent_id) VALUES('电风扇',4);
INSERT tdb_goods_types(type_name,parent_id) VALUES('饮水机',4);
INSERT tdb_goods_types(type_name,parent_id) VALUES('电脑整机',2);
INSERT tdb_goods_types(type_name,parent_id) VALUES('电脑配件',2);
INSERT tdb_goods_types(type_name,parent_id) VALUES('笔记本',9);
INSERT tdb_goods_types(type_name,parent_id) VALUES('超级本',9);
INSERT tdb_goods_types(type_name,parent_id) VALUES('游戏本',9);
INSERT tdb_goods_types(type_name,parent_id) VALUES('CPU',10);
INSERT tdb_goods_types(type_name,parent_id) VALUES('主机',10);
-- 查找所有分类及其父类
SELECT s.type_id,s.type_name,p.type_name FROM tdb_goods_types AS s LEFT JOIN tdb_goods_types AS p ON s.parent_id = p.type_id;
-- 查找所有分类及其子类
SELECT p.type_id,p.type_name,s.type_name FROM tdb_goods_types AS p LEFT JOIN tdb_goods_types AS s ON s.parent_id = p.type_id;
-- 查找所有分类及其子类的数目
SELECT p.type_id,p.type_name,count(s.type_name) AS children_count FROM tdb_goods_types AS p LEFT JOIN tdb_goods_types AS s ON s.parent_id = p.type_id GROUP BY p.type_name ORDER BY p.type_id;
-- 为tdb_goods_types添加child_count字段
ALTER TABLE tdb_goods_types ADD child_count MEDIUMINT UNSIGNED NOT NULL DEFAULT 0;
-- 将刚才查询到的子类数量更新到tdb_goods_types数据表
UPDATE tdb_goods_types AS t1 INNER JOIN ( SELECT p.type_id,p.type_name,count(s.type_name) AS children_count FROM tdb_goods_types AS p
LEFT JOIN tdb_goods_types AS s ON s.parent_id = p.type_id
GROUP BY p.type_name
ORDER BY p.type_id ) AS t2
ON t1.type_id = t2.type_id
SET t1.child_count = t2.children_count;
-- 复制编号为12,20的两条记录
SELECT * FROM tdb_goods WHERE goods_id IN (19,20);
-- INSERT ... SELECT实现复制
INSERT tdb_goods(goods_name,cate_id,brand_id) SELECT goods_name,cate_id,brand_id FROM tdb_goods WHERE goods_id IN (19,20);
-- 查找重复记录
SELECT goods_id,goods_name FROM tdb_goods GROUP BY goods_name HAVING count(goods_name) >= 2;
-- 删除重复记录
DELETE t1 FROM tdb_goods AS t1 LEFT JOIN (SELECT goods_id,goods_name FROM tdb_goods GROUP BY goods_name HAVING count(goods_name) >= 2 ) AS t2 ON t1.goods_name = t2.goods_name WHERE t1.goods_id > t2.goods_id;
INSERT SELECT 插入数据
INSERT [INTO] tbl_name SET col_name={exprDEFAULT},...//可以使用子查询
INSERT [INTO] tbl_name [(col_name,...)] SELECT ...//将查询结果写入数据表
Eg:
INSERT INTO table_name [(column_name)] SELECT column_name2 FROM table_name2 GROUP BY column_name3;
CREATE TABLE IF NOT EXISTS tdb_goods_cates(
cate_id SMALLINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
cate_name VARCHAR(40) NOT NULL
);
SELECT goods_cate FROM tdb_goods GROUP BY goods_cate; //列出所有品牌cate
DESC tdb_goods_cates; //显示出tdb_goods_cates表中的项目名称,与SHOW COLUMNS FROM tdb_goods_cates;作用相同
INSERT tdb_goods_cates(cate_name) SELECT goods_cate FROM tdb_goods GROUP BY goods_cate;//在表tdb_goods_cates中插入tdb_goods中的cate
多表更新:
UPDATE table_references SET col_name1={expr1 | DEFAULT} [,col_name2={expr2 | DEFAULT}]... [WHERE where_condition]
INNER JOIN,内连接
在MySQL中,JOIN, CROSS JOIN 和 INNER JOIN 是等价的。
LEFT [OUTER] JOIN ,左外连接
RIGHT [OUTER] JOIN,右外连接
update tdb_goods inner join tdb_goods_cates on goods_cate=cate_name set goods_cate=cate_id;

tdb_goods:想要更改的表名
inner join: 内连接
tdb_goods_cates: 关联的附表
goods_cate=cate_name 两个表对应列的关系
goods_cate=cate_id; 设置 值

多表更新之一步到位
建表、查询、写入三合一:
CREATE TABLE tdb_goods_brands (
brand_id SMALLINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
brand_name VARCHAR(40) NOT NULL
) SELECT brand_name FROM tdb_goods GROUP BY brand_name;
多表更新:
UPDATE tdb_goods AS g INNER JOIN tdb_goods_brands AS b ON g.brand_name = b.brand_name SET g.brand_name = b.brand_id;
通过ALTER TABLE语句修改数据表结构
ALTER TABLE tdb_goods
CHANGE goods_cate cate_id SMALLINT UNSIGNED NOT NULL,
CHANGE brand_name brand_id SMALLINT UNSIGNED NOT NULL;
PS:
外键,不一定是物理的外键,逻辑的外键也行,当然,物理外键更能保证数据的完整性和一致性。
数字类型的字段占用的空间更小,查询的效率也更高。
连接的语法结构
1.连接
MySQL在SELECT语句、多表更新、多表删除语句中支持JOIN操作。
语法结构
table reference A
{[INNER|CROSS] JOIN | {LEFT|RIGHT} [OUTER] JOIN}
table_reference B
ON condition_expr
2.数据表参照
table_reference
tbl_name [[AS] alias] | table_subquery [AS] alias
数据表可以使用tbl_name AS alias_name 或 tbl_name alias_name赋予别名。
table_subquery可以作为子查询使用在FROM子句中,这样的子查询必须为其赋予别名。
内连接
1.内连接:
在MySQL中JOIN,INNER JOIN,CROSS JOIN是等价的
交集 仅显示A、B两表符合连接条件的记录。不符合连接条件的记录不显示。
例如:SELECT goods_id,goods_name,cate_name FROM tdb_goods INNER JOIN tdb_goods_cate ON tdb_goods.cate_id = tdb_goods_cate.cate_id;
2.外连接:
LEFT JOIN左外连接;RIGHT JOIN右外连接
左外连接:LEFT OUTER JOIN:显示左表的全部记录及右表符合连接条件的记录。
右外连接:RIGHT OUTER JOIN:显示右表的全部记录及左表符合连接条件的记录。
如果使用LEFT JOIN,左表中存在一条记录A,在右表中没有找到相应的记录,则在返回结果用会出现一条只有记录A中的相应字段内容,其他字段都为NULL在记录(RIGHT JOIN类似).
内连接比外链接用的多一些
3.连接条件:
使用ON设定连接条件,也可以用WHERE代替
一般情况下使用 ON:设定连接条件 WHERE:进行结果集记录的过滤
OUTER JOIN
1、LEFT JOIN:显示左表全部和左右符合连接条件的记录
2、RIGHT JOIN:显示左右符合连接条件的记录和右表全部记录
3、如果使用LEFT JOIN,左表中存在一条记录A,在右表中没有找到相应的记录,则在返回结果用会出现一条只有记录A中的相应字段内容,其他字段都为NULL在记录(RIGHT JOIN类似).
-- 查询所有商品的详细信息(通过左外连接实现)
SELECT goods_id,goods_name,cate_name,brand_name,goods_price FROM tdb_goods AS g
LEFT JOIN tdb_goods_cates AS c ON g.cate_id = c.cate_id
LEFT JOIN tdb_goods_brands AS b ON g.brand_id = b.brand_idG;
-- 查询所有商品的详细信息(通过右外连接实现)
SELECT goods_id,goods_name,cate_name,brand_name,goods_price FROM tdb_goods AS g
RIGHT JOIN tdb_goods_cates AS c ON g.cate_id = c.cate_id
RIGHT JOIN tdb_goods_brands AS b ON g.brand_id = b.brand_idG;
查询语句 内连接:显示符合两个表的共同属性的记录;
查询语句 左连接:显示符合左表内的全部内容的记录
查询语句 右连接:显示符合右表内的全部内容的记录
多表连接
多表的连接跟两张表的连接一样
表的连接实质就是外键的逆向约束
*/
Eg:
SELECT goods_id,goods_name,b.cate_name,c.brand_name,goods_price
FROM products AS a INNER JOIN products_cate AS b ON a.goods_cate = b.cate_id
INNER JOIN products_brand AS c ON a.brand_name = c.brand_id;
关于连接的说明
外连接:
以左外连接为例:
A LEFT JOIN B join_condition
数据表B的结果集依赖于数据表A
数据表A的结果集根据左连接条件依赖所有数据表(B表除外)
左外连接条件决定如何检索数据表B(在没有指定WHERE条件的情况下)
如果数据表A的某条记录符合WHERE条件,但是在数据表B不存在符合连接条件的记录,将生成一个所有列为空的额外的B行
内连接:
使用内连接查找的记录在连接数据表中不存在,并且在WHERE子句中尝试一下操作:column_name IS NULL 。如果 column_name 被指定为 NOT NULL,MySQL将在找到符合连接着条件的记录后停止搜索更多的行(查找冲突)

无限分类表
显示表:show clumns from 表名;
无限分类:即在同一张表中既有父类,又有子类
通过在分类表中再增加多一个字段标识其属于哪一个父类的 ID 来实现
可以通过对同一张数据表的自身连接来进行查询,需要对表标识别名

查找显示父级id对应的名称
select s.type_id ,s.type_name,p.type_name As parent_id from tdb_goods_types s left join tdb_goods_types p on s.parent_id=p.type_id;
查找子级对应的名称
select p.type_id ,p.type_name,s.type_name from tdb_goods_types p left join tdb_goods_types s on p.type_id=s.parent_id;
查找有多少子级
select p.type_id ,p.type_name,COUNT(s.type_name) from tdb_goods_types p left join tdb_goods_types s on p.type_id=s.parent_id GROUP BY p.type_name ORDER BY p.type_id;
多表删除
(1)INSERT ... SELECT实现复制
INSERT tdb_goods(goods_name,cate_id,brand_id) SELECT goods_name,cate_id,brand_id FROM tdb_goods WHERE goods_id IN (19,20);
(2)查找重复记录
SELECT goods_id,goods_name FROM tdb_goods GROUP BY goods_name HAVING count(goods_name) >= 2;
(3) 删除重复记录
DELETE t1 FROM tdb_goods AS t1 LEFT JOIN (SELECT goods_id,goods_name FROM tdb_goods GROUP BY goods_name HAVING count(goods_name) >= 2 ) AS t2 ON t1.goods_name = t2.goods_name WHERE t1.goods_id > t2.goods_id;

delete t1 from
从···表中删除
tdb_goods as t1 left join(select goods_id,goods_name from tdb_goods group by goods_name having count(goods_name)>=2) as t2
将tdb_goods看做t1与子查询所得到的表进行左连接
on t1.goods_name=t2.goods_name
t1和t2的连接条件
where t1.goods_id>t2.goods_id;
选出t1表中中满足t1.goods_id>t2.goods_id的

总结
子查询:出现在sq语句中的select子句,而子查询必须要出现在小括号()内,他的外层可以是select语句,insert语句,update语句,delete语句,而且在子查询中可以包含多个关键词:group by ,order by ,limit以及相关函数。。。引发子查询的情况有比较运算符 ,in(NOT)in运算符,exist(NOT EXIST)引发的子查询
连接:连接分为外连接和内连接,内连接主要显示的是左表和右表当中都符合连接条件的记录。外链接有分为左外连接和右外连接,左外连接显示的是左表中的全部记录和右表符合条件的记录,右外连接和左外连接相反,mq中的select,多表更新和删除都可以用到。。内连接,左,右连接。。
create语句中的select ,insert select 语句

编辑:数据库 本文来源:希望指正,二 子查询和连接

关键词: 澳门新濠3559