1. 程式人生 > >mysql 表資料操作

mysql 表資料操作

INSERT INTO USER
VALUES(10,'root','root','[email protected]');


INSERT INTO USER(username,password,email)
VALUES('admin','123','[email protected]');

#插入查詢出來的資料
INSERT INTO USER(username)
SELECT NAME 
FROM account;

UPDATE USER
SET username='robot',PASSWORD='robot'
WHERE username = 'root'

#刪除表中的指定的資料
DELETE FROM USER
WHERE  username ='robot';

#--清空表中的資料
TRUNCATE TABLE USER

#查詢單列
SELECT username
FROM USER;

#查詢多列
SELECT username,PASSWORD
FROM user;


#查詢所有列
SELECT * 
from USER;

#按id降序排序
SELECT * 
from USER ORDER BY id DESC;

#查詢不同的值
#DISTINCT 用於返回唯一不同的值。它作用於所有列,也就是說所有列的值都相同才算相同。

SELECT DISTINCT  username
FROM USER

-- 返回前3行
SELECT * FROM USER LIMIT 3;
SELECT * FROM USER LIMIT 0,3;

-- 返回第3-5行
SELECT * FROM USER LIMIT 2,3;

-- 返回3-6行
SELECT * FROM USER LIMIT 2,4;



-- WHERE 條件查詢
SELECT * FROM USER
WHERE username = 'admin';

UPDATE USER
SET PASSWORD = '123'
WHERE username = 'root';

DELETE FROM USER
WHERE username = 'sadfa2';



--  IN 和 BETWEEN 限定範圍
/*
IN 操作符在 WHERE 子句中使用,作用是在指定的幾個特定值中任選一個值。
BETWEEN 操作符在 WHERE 子句中使用,作用是選取介於某個範圍內的值
*/

-- 查詢id=11 和13的資料
SELECT * from USER
WHERE id  in ('11','13')

-- 查詢10到13的資料
SELECT * FROM USER
WHERE id BETWEEN 10 AND 13;


-- -----------------------------------
-- -----------------------------------
CREATE TABLE `products` (
  `prod_id` int(10) NOT NULL,
  `prod_name` varchar(255) NOT NULL,
  `prod_price` decimal(10,0) NOT NULL,
	`vend_id`  varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- AND、OR、NOT是用於對過濾條件的邏輯處理

SELECT prod_id, prod_name, prod_price
FROM products
WHERE vend_id  = 'DLL01' AND prod_price <= 200;



SELECT prod_id, prod_name, prod_price
FROM products
WHERE vend_id = 'DLL01' OR vend_id = 'BRS01';


SELECT *
FROM products
WHERE prod_price NOT BETWEEN 100 AND 200;

-- -------------------------------
-- ---------------------------------

-- LIKE 模糊查詢

-- 萬用字元 %  表示任何字元出現任意次數。
-- 萬用字元 _   表示任何字元出現一次
SELECT prod_id, prod_name, prod_price
FROM products
WHERE prod_name LIKE '%dfg%';



SELECT prod_id, prod_name, prod_price
FROM products
WHERE prod_name LIKE '_fgash';