一、
建立一個表:
CREATE TABLE `flower` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`color` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1
插入如下資料:
1 blue
2 red
3 blue
4 red
5 blue
那麼現在要求使用一個sql語句統計出來所有的red和blue的個數,
可以如下:
select
sum( case when color='red' then 1 else 0 end)as 'red',
sum( case when color='blue' then 1 else 0 end)as 'blue'
from flower
select count(1) as cnt,color from flower group by color
上面兩個都可以。
一般公司都會把資料庫作為儲存介質而非邏輯運算。在這個例子中分多次起初資料。其實資料庫是可以做到一次取出這類資料的。
二、
在一個更新語句中使用查詢語句
建立表如下:
CREATE TABLE `counter` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`counter` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1018 DEFAULT CHARSET=latin1
錄入如下資料:
1 83
3 4
5 45
6 32
7
8
9 83
10 4
現在如果想把id為1的counter列設定為所有的counter之和。那麼,對於其他資料庫產品,可以如下:
update counter c set counter=(select sum(counter) from counter)
但是,要注意的是,mysql根本就不支援在update語句中使用select語句【對於同一個表操作的情況】。
那麼,在mysql下可以使用一個串連,這麼寫:
update counter c inner join (select sum(counter) as count_ from counter )as t set counter= t.count_ where c.id=1
三、
查詢id大於5的個數
有一個表,id自增長,想查詢id大於5的,那麼很簡單的可以寫出來一個sql:
select count(*) from table where id > 5
但是,這麼寫有什麼問題呢。
在innodb表引擎中,這是必定要掃描全表的。【勘誤2012-12-17---這裡不知道當時腦袋秀逗了?怎麼會寫出這麼傻x的錯誤。innodb只要有索引就不會全表掃描】
在myisam表引擎中,使用explain可以看到,這個sql語句訪問了很多資料。而非僅僅小於5的那幾個資料。可以最佳化如下:
explain select (select count(*) from counter )- count(*) from counter where id<=5
再次explain可以看到,Select tables optimized away,這次的sql使用了myisam的儲存表資料個數的強項。