MySQL 是最受歡迎的關聯式資料庫管理系統 (RDBMS) 之一,用於 Web 應用程式和其他資料驅動應用程式。無論您是初學者還是想要提高 MySQL 技能的人,了解基本查詢都是至關重要的。本部落格將引導您完成一些基本的 MySQL 查詢,可用於資料庫操作、表格操作和資料管理。
首先,您需要一個資料庫來儲存表格和資料。建立資料庫很簡單:
CREATE DATABASE my_database;
建立資料庫後,使用以下查詢來選擇它:
USE my_database;
如果需要刪除資料庫,請使用以下指令:
DROP DATABASE my_database;
表格是儲存資料的地方。您可以建立包含特定列的表,如下所示:
CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100), email VARCHAR(100), age INT );
要查看所選資料庫中的所有資料表:
SHOW TABLES;
如果你想了解表格的結構,可以描述它:
DESCRIBE users;
如果您需要透過新增或變更列來修改表格:
ALTER TABLE users ADD phone VARCHAR(15);
ALTER TABLE users MODIFY age TINYINT;
刪除表:
DROP TABLE users;
將資料加入表中:
INSERT INTO users (name, email, age) VALUES ('John Doe', 'john@example.com', 25);
從表格中擷取資料:
SELECT name, email FROM users WHERE age > 20;
要從表格中檢索所有資料:
SELECT * FROM users;
更新表中的資料:
UPDATE users SET age = 26 WHERE name = 'John Doe';
要從表格中刪除資料:
DELETE FROM users WHERE name = 'John Doe';
使用WHERE子句依照特定條件過濾記錄:
SELECT * FROM users WHERE age > 20;
使用 AND 或 OR 組合多個條件:
SELECT * FROM users WHERE age > 20 AND name = 'John Doe';
根據數值清單選擇資料:
SELECT * FROM users WHERE age IN (20, 25, 30);
過濾一定範圍內的資料:
SELECT * FROM users WHERE age BETWEEN 20 AND 30;
使用 LIKE 子句搜尋模式:
SELECT * FROM users WHERE name LIKE 'J%';
過濾具有 NULL 或 NOT NULL 值的記錄:
SELECT * FROM users WHERE email IS NULL;
計算行數:
SELECT COUNT(*) FROM users;
計算列的總和:
SELECT SUM(age) FROM users;
求一列的平均值:
SELECT AVG(age) FROM users;
找出列的最大值或最小值:
SELECT MAX(age) FROM users;
SELECT MIN(age) FROM users;
依照一列或多列將資料分組:
SELECT age, COUNT(*) FROM users GROUP BY age;
濾波分組資料:
SELECT age, COUNT(*) FROM users GROUP BY age HAVING COUNT(*) > 1;
依升序或降序對資料進行排序:
SELECT * FROM users ORDER BY age DESC;
從多個表格中取得滿足條件的資料:
SELECT users.name, orders.order_date FROM users INNER JOIN orders ON users.id = orders.user_id;
從左表中取得資料並從右表中取得符合的行:
SELECT users.name, orders.order_date FROM users LEFT JOIN orders ON users.id = orders.user_id;
從右表中取得資料並從左表中取得符合的行:
SELECT users.name, orders.order_date FROM users RIGHT JOIN orders ON users.id = orders.user_id;
使用子查詢過濾結果:
SELECT name FROM users WHERE id = (SELECT user_id FROM orders WHERE order_id = 1);
使用子查詢計算值:
SELECT name, (SELECT COUNT(*) FROM orders WHERE users.id = orders.user_id) AS order_count FROM users;
根據查詢建立虛擬表:
CREATE VIEW user_orders AS SELECT users.name, orders.order_date FROM users INNER JOIN orders ON users.id = orders.user_id;
Delete a view:
DROP VIEW user_orders;
Improve query performance by creating an index:
CREATE INDEX idx_name ON users (name);
Remove an index:
DROP INDEX idx_name ON users;
Understanding these basic MySQL queries is essential for anyone working with relational databases. Whether you are managing data, optimizing queries, or ensuring data integrity, these commands form the foundation of your MySQL skills. By mastering them, you'll be well-equipped to handle most database-related tasks with ease.
以上是基本 MySQL 查詢:綜合指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!