跳到主要內容區塊
:::
首頁 文章分享列表 文章分享

MySQL 查詢、插入、更新、刪除基本語法

對於 MySQL 資料庫資料操作的基本語法大全

select 查詢

撈取資料表中所有欄位及資料:

select * from `資料表名稱`;
select * from `news`;

指定撈取部分欄位:

select `欄位一`, `欄位二` from `資料表名稱`;
select `id`, `name` from `news`;

where 條件

撈取欄位一等於 "1" 的資料

select * from `資料表名稱` where `欄位一` = 1;
select * from `news` where `id` = 1;

撈取欄位一等於"1",且欄位二大於"10"的資料

select * from `資料表名稱` where `欄位一` = 1 and `欄位二` > 10;
select * from `news` where `id` = 1 and `pageviews` > 10;

where in 條件 包含

撈取欄位一等於 "1" 或 "2" 或 "3" 的資料

select * from `資料表名稱` where `欄位一` in (1, 2, 3);
select * from `news` where `id` in (1, 2, 3);

where is null 條件 等於 null

撈取欄位一為 "null" 的資料

select * from `資料表名稱` where `欄位一` is null;
select * from `news` where `id` is null;

where is not null 條件 不等於 null

撈取欄位一不是 "null" 的資料

select * from `資料表名稱` where `欄位一` is not null;
select * from `news` where `id` is not null;

order by 排序

撈取資料並以欄位一正向排序

select * from `資料表名稱` order by `欄位一` asc;
select * from `news` order by `id` asc;

撈取資料並以欄位一反向排序

select * from `資料表名稱` order by `欄位一` desc;
select * from `news` order by `id` desc;

撈取資料並以欄位一中文排序

select * from `資料表名稱` order by binary(CONVERT(`欄位一` using big5))
select * from news order by binary(CONVERT(`name` using big5))

limit 筆數限制

取得五筆資料

SELECT * FROM `資料表名稱` LIMIT 5
SELECT * FROM `news` LIMIT 5

取得五筆資料,並由第十筆開始取得(得到排序中第10~15筆)

SELECT * FROM `資料表名稱` LIMIT 5,10
SELECT * FROM `news` LIMIT 5,10

group 群組

取得資料並將欄位一相同的資料合併為一筆

SELECT * FROM `資料表名稱` GROUP BY `欄位一`;
SELECT * FROM `news` GROUP BY `release_date`;

計算相同欄位一相同資料的欄位加總(取得每天新聞各有幾筆)

SELECT COUNT(*) FROM `資料表名稱` GROUP BY `欄位一`;
SELECT COUNT(*) FROM `news` GROUP BY `release_date`;

insert 插入資料

插入一筆新資料

insert into `資料表名稱`(`欄位一`,`欄位二`) VALUES ('欄位一資料', '欄位二資料');
insert into `news`(`title`,`release_date`) VALUES ('焦點新聞快報', '1990-05-09');

ALTER TABLE 插入一個新欄位

ALTER TABLE `資料表名稱` ADD `新增欄位名稱` 新增欄位型態 新增欄位預設值 COMMENT '新增欄位說明';
ALTER TABLE `news` ADD deleted_at TIMESTAMP NULL COMMENT '刪除時間';

update 更新資料

UPDATE `資料表名稱` SET `欄位一` = '欄位一資料', `欄位二` = '欄位二資料';
UPDATE `news` SET `title` = '焦點新聞快報!', `release_date` = '2020-02-02';

delete 刪除資料

刪除資料表中欄位一等於 "1" 的所有資料

delete from `資料表名稱` WHERE `欄位ㄧ` = 1;
delete from `news` WHERE `id` = 1;

truncate 清空

清空資料表中的所有資料

truncate table `資料表名稱`;
truncate table `news`;

 

這篇文章是否對您有幫助?
Line線上詢價 線上詢價
電子郵件
電話
聯繫我們