1.檢索包含最大或最小值的行。
MIN([distinct] expr) , MAX([distinct] expr)
select student_name, min(score),max(score) from student group by student_name;
2. rand & rand (n) 提取隨機行。
select * from t1 order by rand(); 隨機檢索表數據。
select * from t1 order by rand() limit 20; 隨機提取一組20個行的數據。
3. 利用group by 的with rollup 子句做統計
create table sales
(
year int not null,
country varchar(20) not null,
product varchar(20) not null,
profit int
);
select year,sum(profit)from sales group by year;
select year,sum(profit)from sales group by year with rollup;
select year,country,product,sum(profit) from sales group by year,country,product;
select year,country,product,sum(profit) from sales group by year,country,product with rollup;
insert into sales values(2004,'china','tnt2004',2001);
insert into sales values(2004,'china','tnt2004',2002);
insert into sales values(2004,'china','tnt2004',2003);
insert into sales values(2005,'china','tnt2005',2004);
insert into sales values(2005,'china','tnt2005',2005);
insert into sales values(2005,'china','tnt2005',2006);
insert into sales values(2005,'china','tnt2005',2007);
insert into sales values(2005,'china','tnt2005',2008);
insert into sales values(2005,'china','tnt2005',2009);
insert into sales values(2006,'china','tnt2006',2010);
insert into sales values(2006,'china','tnt2006',2011);
insert into sales values(2006,'china','tnt2006',2012);
select year,country,product,sum(profit) from sales group by year,country,product;
select year,country,product,sum(profit) from sales group by year,country,product with rollup;
SELECT year,country,product,SUM(profit) FROM sales GROUP BY year,country,product WITH ROLLUP LIMIT 5;
rollup 與 order by 互斥。
數據庫對象名的大小寫問題
在MySQL中,數據庫對應的是數據目錄中的一個目錄,而表對應的是一個或多個文件。因此會根據操作系統對大小寫的敏感度不同而不同。
列,索引,存儲子程序和觸發器在任何平臺上對大小寫都不敏感,列別名也不敏感。默認情況下,表別名在unix中是敏感的。
lower_case_tables_name
0:使用create table或create database。
按指定的大小寫在硬盤上保存。對大小寫敏感。(Unix默認)。如果再對大小寫不敏感的FS上強制將此參數設置爲0,並且使用不同大小寫訪問MyISAM表,會導致索引損壞。
1:表名在硬盤上以小寫保存。大小寫敏感。(Windows 和 MaxOS 默認)
2:按指定的大小寫保存。但是MySQL將他們轉換成小寫,便於查找。大小寫敏感。
此參數只在需要在不同平臺上轉移表使用。
在任何操作系統上都可以使用 =1,不利之處是show tables/show databases 的時候看不出原本的大小寫。
在unix上=0,在Windows上=2,可以保留數據庫名的大小寫,不利之處是要確保始終使用正確的大小寫查詢。
例外,如果是InnoDB表,在任何平臺上均應設置爲1,強制轉換爲小寫。
在Unix中,將此參數設置爲1 ,重啓mysqld之前,必須將舊的數據庫名和表名改爲小寫。
使用外鍵需要注意的地方
在MySQL中, InnoDB表支持對外部關鍵字約束條件的檢查。
對於除InnoDB類型的表,當使用REFERENCES tbl_name(col_name)子句定義列時可以使用外部關鍵字,該子句沒有實際的效果,只作爲備忘錄或註釋來提醒,你目前正定義的列指向另一個表中的一個列。執行該語句時,實現下面很重要:
MySQL不執行表tbl_name 中的動作, 例如作爲你正定義的表中的行的動作的響應而刪除行;換句話說,該句法不會致使ON DELETE或ON UPDATE行爲(如果你在REFERENCES子句
中寫入ON DELETE或ON UPDATE子句,將被忽略)。
該句法可以創建一個column;但不創建任何索引或關鍵字。
如果用該句法定義InnoDB表,將會導致錯誤。