下面是一些學習如何用MySQL解決一些常見問題的例子
一些例子使用數據庫表
你能這樣創建例子數據庫表
CREATE TABLE shop (
article INT(
dealer CHAR(
price DOUBLE(
PRIMARY KEY(article
INSERT INTO shop VALUES
(
(
好了
SELECT * FROM shop
+
| article | dealer | price |
+
|
|
|
|
|
|
|
+
SELECT MAX(article) AS article FROM shop
+
| article |
+
|
+
在ANSI
SELECT article
FROM shop
WHERE price=(SELECT MAX(price) FROM shop)
在MySQL中(還沒有子查詢)就用
用一個SELECT語句從表中得到最大值
使用該值編出實際的查詢
SELECT article
FROM shop
WHERE price=
另一個解決方案是按價格降序排序所有行並用MySQL特定LIMIT子句只得到的第一行
SELECT article
FROM shop
ORDER BY price DESC
LIMIT
注意:如果有多個最貴的文章( 例如每個
SELECT article
FROM shop
GROUP BY article
+
| article | price |
+
|
|
|
|
+
在ANSI SQL中
SELECT article
FROM shop s
WHERE price=(SELECT MAX(s
FROM shop s
WHERE s
在MySQL中
得到一個表(文章
對每篇文章
這可以很容易用一個臨時表做到
CREATE TEMPORARY TABLE tmp (
article INT(
price DOUBLE(
LOCK TABLES article read;
INSERT INTO tmp SELECT article
SELECT article
WHERE shop
UNLOCK TABLES;
DROP TABLE tmp;
如果你不使用一個TEMPORARY表
是的
SELECT article
SUBSTRING( MAX( CONCAT(LPAD(price
FROM shop
GROUP BY article;
+
| article | dealer | price |
+
|
|
|
|
+
最後例子當然能通過在客戶程序中分割連結的列使它更有效一點
不需要外鍵聯結
MySQL唯一不做的事情是CHECK以保證你使用的鍵確實在你正在引用表中存在
CREATE TABLE persons (
id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT
name CHAR(
PRIMARY KEY (id)
);
CREATE TABLE shirts (
id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT
style ENUM(
color ENUM(
owner SMALLINT UNSIGNED NOT NULL REFERENCES persons
PRIMARY KEY (id)
);
INSERT INTO persons VALUES (NULL
INSERT INTO shirts VALUES
(NULL
(NULL
(NULL
INSERT INTO persons VALUES (NULL
INSERT INTO shirts VALUES
(NULL
(NULL
(NULL
(NULL
SELECT * FROM persons;
+
| id | name |
+
|
|
+
SELECT * FROM shirts;
+
| id | style | color | owner |
+
|
|
|
|
|
|
|
+
SELECT s
WHERE p
AND s
AND lor <>
+
| id | style | color | owner |
+
|
|
|
+
From:http://tw.wingwit.com/Article/program/MySQL/201311/29382.html