一些经典的SQL编程问题
数字辅助表是一个只包含从1到N的N个整数的简单表,N通常很大。数字辅助表是一个非常强大的工具,所以我们创建一个持久的数字辅助表:
- CREATE TABLE Nums(
-
a INT UNSIGNED NOT NULL PRIMARY KRY
-
)ENGINE=InnoDB;
-
-
CREATE PRODURE CreateNums (t INT UNSIGNED )
-
BEGIN
-
DECLARE s INT UNSIGNED DEFAULT 1;
-
TRUNCATE TABLE Nums;
-
INSERT INTO Nums SELECT s;
-
WHILE s*2 <= t DO
-
BEGIN
-
INSERT INTO Nums SELECT a+s FROM Nums;
-
SET s = s*2
-
END;
-
END WHILE;
- END;
二 连续范围
-
CREATE TABLE t (a INT UNSIGNED NOT NULL PRIMARY KEY);
-
INSERT INTO t VALUES(1);
-
INSERT INTO t VALUES(2);
-
INSERT INTO t VALUES(3);
-
INSERT INTO t VALUES(100);
-
INSERT INTO t VALUES(101);
-
INSERT INTO t VALUES(103);
-
INSERT INTO t VALUES(104);
- INSERT INTO t VALUES(105);
-
SELECT MIN(a) start,MAX(a) end FROM (
-
SELECT a,rn,a-rn AS diff
-
FROM (SELECT a,@a:=@a+1 rn FROM t,(SELECT @a:=0) AS a)
-
AS b
-
)AS c
- GROUP BY diff;
三 最小缺失值
点击(此处)折叠或打开
-
CREATE TABLE x(
-
a INT UNSIGNED PRIMARY KEY,
-
b CHAR(1) NOT NULL
-
)ENGINE = InnoDB;
-
-
INSERT INTO x SELECT 3,‘a‘;
-
INSERT INTO x SELECT 4,‘b‘;
-
INSERT INTO x SELECT 6,‘c‘;
- INSERT INTO x SELECT 7,‘d‘;
如果当前表的数据为1、2、3、4、6、7,则返回5。
解决方案如下:
-
SELECT
-
CASE
-
WHEN NOT EXISTS (SELECT a FROM x WHERE a=1)THEN 1
-
ELSE
-
(SELECT MIN(a)+1 AS missing
-
FROM x AS A
-
WHERE NOT EXISTS
-
(SELECT * FROM x AS B
-
WHERE A.a+1=B.a))
- END AS missing;
若要对最小缺失值进行补缺操作,解决方案如下:
-
INSERT INTO x
-
SELECT
-
CASE
-
WHEN NOT EXISTS (SELECT a FROM x WHERE a=1)THEN 1
-
ELSE
-
(SELECT MIN(a)+1 AS missing
-
FROM x AS A
-
WHERE NOT EXISTS
-
(SELECT * FROM x AS B
- WHERE A.a+1=B.a)) END AS missing, ‘p‘;
四 获取行号
行号是指按顺序为查询结果集的行分配的连续整数。
-
CREATE TABLE sales (
-
empid varchar(10) NOT NULL,
-
mgrid varchar(10) NOT NULL,
-
qty` int(11) NOT NULL,
-
PRIMARY KEY (empid)
-
);
-
-
INSER INTO salses VALUES(‘A‘,Z‘,300);
-
INSER INTO salses VALUES(‘B‘,X‘,100);
-
INSER INTO salses VALUES(‘C‘,Y‘,100);
-
INSER INTO salses VALUES(‘D‘,Z‘,300);
-
INSER INTO salses VALUES(‘E‘,X‘,200);
- INSER INTO salses VALUES(‘F‘,Z‘,100);
-
SELECT empid,
-
(SELECT COUNT(*) FROM sales AS T2
-
WHERE T2.empid <= T1.empid) AS rownum
- FROM sales AS T1;
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。