1. 程式人生 > >MySQL查詢例項

MySQL查詢例項

單表查詢
查詢所有列

1 SELECT * FROM product;

查詢指定列

1 SELECT pro_name,price,pinpai FROM product;

新增常量列

1 SELECT pro_name AS '產品名稱',price FROM product;

建立學生表

 
 1 CREATE TABLE stu(
 2      sid  INT,
 3      sname  VARCHAR(10),
 4      sex  VARCHAR(2),
 5      servlet  DOUBLE,
 6      jsp   DOUBLE,
 7      html  DOUBLE 
 8 )
 9 SHOW TABLES;
10 INSERT INTO stu VALUES(1,'佩奇','女',100,60,80);
11 INSERT INTO stu VALUES(2,'喬治','男',25,58,100);
12 INSERT INTO stu VALUES(3,'薛之謙','男',100,100,100);
13 INSERT INTO stu VALUES(4,'李榮浩','男',90,90,90);
14 INSERT INTO stu(sid,sname,servlet,html) VALUES(5,'於文文',90,90);
15 INSERT INTO stu(sid,sname,servlet,html) VALUES(6,'',90,10);
16 SELECT * FROM stu;
 

查詢時合併列

1 SELECT sname,(servlet+jsp+html) AS '總成績' FROM stu;

查詢時去除重複記錄

1 SELECT DISTINCT sex FROM stu;

條件查詢

1 SELECT * FROM stu WHERE sex='男' AND sname='薛之謙';
2 SELECT * FROM stu WHERE sex='女' OR sname='薛之謙';

查詢大於70分的學生

1 SELECT * FROM stu WHERE servlet>60;

查詢jsp成績不等於60分的學生

1 SELECT * FROM stu WHERE jsp<>60;

查詢html成績在60和100之間的學生

1 SELECT * FROM stu WHERE html BETWEEN 60 AND 100;
2 SELECT * FROM stu WHERE html >= 60 AND html<=100;

查詢sex為null的學生

1 SELECT * FROM stu WHERE sex IS NULL;
2 SELECT * FROM stu WHERE sex IS NOT NULL;

 查詢sname是空字串的學生

1 SELECT * FROM stu WHERE sname='';
2 SELECT * FROM stu WHERE sname<>'';

查詢sex不為空的學生

1 SELECT * FROM stu WHERE sex IS NOT NULL AND sex<>'';

查詢所有產品中帶有索尼的產品

1 SELECT * FROM product WHERE pro_name LIKE '%索尼%';

 查詢班級中所有兩個字的同學

1 SELECT * FROM stu WHERE sname LIKE '__';

 聚合函式:查詢stu表中所有學生的servlet總成績

1 SELECT SUM(servlet) FROM stu;

聚合函式:查詢stu表中所有學生的servlet平均成績

1 SELECT AVG(servlet) FROM stu;

 聚合函式:查詢stu表中jsp課程中的最高分

1 SELECT MAX(JSP) FROM stu;

最低分

1 SELECT MIN(jsp) FROM stu;

查詢stu表中有多少人

1 SELECT COUNT(*) FROM stu;(每列統計 取最大值)

 分頁

1 SELECT * FROM stu LIMIT 0,2;

查詢排序

1 SELECT * FROM stu ORDER BY html ASC;(升序)
2 SELECT * FROM stu ORDER BY html DESC;(倒序)

查詢stu表中所有男同學的html成績排序

1 SELECT * FROM stu WHERE sex='男' ORDER BY html;
2 SELECT * FROM stu ORDER BY jsp ASC,html DESC;

查詢男女人數

1 SELECT sex,COUNT(*) FROM stu GROUP BY sex; 

查詢總人數大於2的性別

1 SELECT SEX,COUNT(*) FROM STU GROUP BY sex HAVING COUNT(*)>2;