CS-Notes/notes/SQL 语法.md
2018-02-22 14:47:22 +08:00

12 KiB
Raw Blame History

????

????????????????¦Ä›¥???›¥???????????????????¦Ç?????????????????????

??????????????????????????????????????????????????????????§Ö?????????

SQL??Structured Query Language)????? SQL ?? ANSI ???????????????? ANSI SQL?????? DBMS ??????????????? PL/SQL??Transact-SQL ???

???

SQL ????????§³§Õ???????????????????????????????????????? DBMS ??????¨¢?

DISTINCT

????????????¦±??????????????§µ????????????§Ö????????????????

SELECT DISTINCT col1, col2
FROM mytable;

LIMIT

????????????????????????????????????????????§µ??? 0 ????????????????????????????

????? 5 ?§Ö? SQL??

SELECT *
FROM mytable
LIMIT 5;
SELECT *
FROM mytable
LIMIT 0, 5;

????? 3 ~ 5 ?§µ?

SELECT *
FROM mytable
LIMIT 2, 3;

???

# ???
SELECT *
FROM mytable -- ???
/* ???1
   ???2 */

????

ASC?????????? DESC??????

?????????§ß???????

SELECT *
FROM mytable
ORDER BY col1 DESC, col2 ASC;

????

????¨°??????????????????????????????§Û?????????????????????×Ï??????????????????????????????

SELECT *
FROM mytable
WHERE col IS NULL;

?¡À?????? WHERE ????????????

?????? ???
= < > ???? §³?? ????
<> != ??????
<= !> §³?????
>= !< ???????
BETWEEN ??????????
IS NULL ?NULL?

????????NULL ?? 0 ????????????????

AND OR ??????????????????????????? AND?????????????????<3F>p????? AND ?? OR ????????? () ?????????????

IN ??????????????????????????????? SELECT ????????????????????????

NOT ????????????????????

????

??????????????????§µ?????????????¦±?

  • % ??? >=0 ????????????????? *??

  • _ ??? ==1 ????????????????? .??

  • [ ] ??????²®????????????????? ^ ?????????§Ù?

??? Like ?????????????

SELECT *
FROM mytable
WHERE col LIKE '[^AB]%' -- ????AB????????????

?????????????????¦Ë????????????????

???????

?????????????????????????????????????????????????????????????????????????????????????????????????

???????????????? AS ????????????????????????????????????

SELECT col1*col2 AS alias
FROM mytable

Concat() ??????????????¦±?????????????????????????§á?????????????????§»???????????? TRIM() ?????????¦Â???

SELECT Concat(TRIM(col1), ' (', TRIM(col2), ')')
FROM mytable

????

???? DBMS ???????????????????????????

???????

???? ???
LEFT() RIGHT() ?????????????
LOWER() UPPER() ????§³§Õ?????§Õ
LTRIM() RTIM() ???????????????
LENGTH() ????
SUNDEX() ?????????

???§µ?SOUNDEX() ????????????????????????????????????????????????????????????????????

SELECT *
FROM mytable
WHERE SOUNDEX(col1) = SOUNDEX('apple')

??????????

????????YYYY-MM-DD

???????HH:MM:SS

?? ?? ? ??
AddDate() ??????????????????
AddTime() ?????????????????
CurDate() ??????????
CurTime() ?????????
Date() ???????????????????
DateDiff() ???????????????
Date_Add() ?????????????????
Date_Format() ??????????????????????
Day() ????????????????????
DayOfWeek() ?????????????????????????
Hour() ???????????§³?????
Minute() ?????????????????
Month() ?????????????¡¤????
Now() ??????????????
Second() ???????????????
Time() ????????????????????
Year() ??????????????????
mysql> SELECT NOW();
        -> '2017-06-28 14:01:52'

???????

???? ???
SIN() ????
COS() ????
TAN() ????
ABS() ?????
SQRT() ?????
MOD() ????
EXP() ???
PI() ?????
RAND() ?????

????

?? ?? ? ??
AVG() ??????§Ö?????
COUNT() ??????§Ö?????
MAX() ??????§Ö?????
MIN() ??????§Ö???§³?
SUM() ???????????

AVG() ????? NULL ?§³?

DISTINCT ??????????????????

SELECT AVG(DISTINCT col1) AS avg_col
FROM mytable

????

?????????????????????????§³?

????????????????????????§Õ???????????????????????

?? col ????????????

SELECT col, COUNT(*) AS num
FROM mytable
GROUP BY col;

WHERE ?????§µ?HAVING ??????ï…?§Û?????????????????

SELECT col, COUNT(*) AS num
FROM mytable
WHERE col > 2
GROUP BY col
HAVING COUNT(*) >= 2;

GROUP BY ???????????????¦²??? ORDER BY ??????????????????????

SELECT col, COUNT(*) AS num
FROM mytable
GROUP BY col
ORDER BY num;

????ÕÇ??

  1. GROUP BY ???????? WHERE ??????ORDER BY ???????
  2. ????????????????SELECT ????§Ö????§Ø??????? GROUP BY ????§Ú?????
  3. NULL ???§Ý????????ï”
  4. ????? SQL ??????? GROUP BY ?§à??§á??????????????

????

????????????????§³?

???????????????? WHRER ?????????????

SELECT *
FROM mytable1
WHERE col1 IN (SELECT col2
                 FROM mytable2);

?????????????????????????????????????????????????????????¦²?

SELECT cust_name, (SELECT COUNT(*)
                   FROM Orders
                   WHERE Orders.cust_id = Customers.cust_id)
                   AS orders_num
FROM Customers
ORDER BY cust_name;

????

??????????????????? JOIN ???????????????????? ON??

????????<3F>I?????????????????§¹?????????

?????? AS ??????????????¦Ê???????????????????????????? SQL ???????????????

??????

??????????????????? INNER JOIN ??????

select a, b, c
from A inner join B
on A.key = B.key

??????????? INNER JOIN????????????????? WHERE ?§ß???????????????????????????????????

select a, b, c
from A, B
where A.key = B.key

?????????????????¡¤???????????

??????

??????????????????????????????????????????

??????????????????????????????????????? Jim ????????????????????????

?????·Ú

select name
from employee
where department = (
      select department
      from employee
      where name = "Jim");

??????·Ú

select name
from employee as e1, employee as e2
where e1.department = e2.department
      and e1.name = "Jim";

??????????????§¹????

???????

????????????????????????????????????????§á????§Ø????

?????????????????????????????????§µ?????????????????????????§µ???????????????????

select *
from employee natural join department;

??????

?????????????§Û???????§»?§³???????????????????????????????????????????????????????§³?

???????§Û???????????????????§Ø???????????

select Customers.cust_id, Orders.order_num
   from Customers left outer join Orders
   on Customers.cust_id = Orders.curt_id

??????????????????????????????

select Customers.cust_id,
       COUNT(Orders.order_num) as num_ord
from Customers left outer join Orders
on Customers.cust_id = Orders.curt_id
group by Customers.cust_id

?????

??? UNION ??????????????????????????????????§³?????????????????

???????????§µ???????????????§µ???? UNION ALL ??

????????? ORDER BY ??????????¦Ë?????????

SELECT col
FROM mytable
WHERE col = 1
UNION
SELECT col
FROM mytable
WHERE col =2;

????

???????

INSERT INTO mytable(col1, col2)
VALUES(val1, val2);

?????????????????

INSERT INTO mytable1(col1, col2)
SELECT col1, col2
FROM mytable2;

????????????????????¡À?

CREATE TABLE newtable AS
SELECT * FROM mytable;

????

UPDATE mytable
SET col = val
WHERE id = 1;

???

DELETE FROM mytable
WHERE id = 1;

TRUNCATE TABLE ?????????????????????§³?

????????????????????? WHERE ????????????????????????????????? SELECT ?????§Ó????????????????

??????

CREATE TABLE mytable (
  id INT NOT NULL AUTO_INCREMENT,
  col1 INT NOT NULL DEFAULT 1,
  col2 VARCHAR(45) NULL,
  col3 DATE NULL,
  PRIMARY KEY (`id`));

????

?????

ALTER TABLE mytable
ADD col CHAR(20);

?????

ALTER TABLE mytable
DROP COLUMN col;

?????

DROP TABLE mytable;

???

?????????????????????????????????????????????????????????????????????????

???????????????

  1. ?????? SQL ?????????¿y???????
  2. ???????????????????
  3. ???????????????????????????????????
  4. ????????????????
CREATE VIEW myview AS
SELECT Concat(col1, col2) AS concat_col, col3*col4 AS count_col
FROM mytable
WHERE col5 = val;

?ݴ????

?ݴ????????????????? SQL ????????????

???ݴ???????

  1. ???????????›¥?????§µ???????????????????
  2. ??????????
  3. ?????????????????§Ü????????

?????ݴ????

???????§Õ????›¥??????????????????????????????? ; ????????????›¥???????????????????????????????????????????????????

???? in??out ?? inout ?????????

???????????????? select into ???

?????????????????????????????????

delimiter //

create procedure myprocedure( out ret int )
    begin
        declare y int;
        select sum(col1)
        from mytable
        into y;
        select y*y into ret;
    end //
delimiter ;
call myprocedure(@ret);
select @ret;

?¦Á?

??›¥??????????¦Á??????????????????????????

?¦Á??????????????????????????????????§Ö??????§ß????????????

????¦Á????????Ñs

  1. ?????¦Á????????????????????????
  2. ???¦Á?
  3. ????????
  4. ????¦Á?
delimiter //
create procedure myprocedure(out ret int)
    begin
        declare done boolean default 0;

        declare mycursor cursor for
        select col1 from mytable;
        # ?????????continue handler???? sqlstate '02000' ??????????????????? set done = 1
        declare continue handler for sqlstate '02000' set done = 1;

        open mycursor;

        repeat
            fetch mycursor into ret;
            select ret;
        until done end repeat;

        close mycursor;
    end //
 delimiter ;

??????

?????????????????????????????????§µ?DELETE??INSERT??UPDATE

???????????????????????????????????§µ????????? BEFORE ??????????????? AFTER ??????BEFORE ??????????????????

INSERT ???????????????? NEW ???????

CREATE TRIGGER mytrigger AFTER INSERT ON mytable
FOR EACH ROW SELECT NEW.col;

DELETE ???????????????? OLD ???????????????????

UPDATE ???????????????? NEW ???????? OLD ??????????? NEW ????????????? OLD ????????

???????????????????????????????????????????§³?

MySQL ?????????????????? CALL ??? ?????????????ݴ?????

??????

????????

  1. ????transaction?????? SQL ???
  2. ?????rollback?????????? SQL ????????
  3. ????commit?????¦Ä?›¥?? SQL ?????§Õ????????
  4. ??????savepoint????????????????????¦Ë????placeholder?????????????????????????????????????????

??????? SELECT ??????? SELECT ????????‰Ù???????? CRETE ?? DROP ???

MySQL ?????????????????????????????????????????¦±??????? START TRANSACTION ??????????????????? COMMIT ?? ROLLBACK ?????§Ü??????????????????????????

??????? autocommit ? 0 ????????????????? autocommit ??????? 1 ???????autocommit ???????????????????????????????

???????????????ROLLBACK ?????? START TRANSACTION ????????????????????????? ROLLBACK ??????????????????????????

START TRANSACTION
// ...
SAVEPOINT delete1
// ...
ROLLBACK TO delete1
// ...
COMMIT

?????

????????

  1. ???????????????????
  2. ??????????????????????????
  3. §µ??????????¦Á?????????????????î•

?????????????????§µ?????????????????

CREATE TABLE mytable
(col VARCHAR(10) CHARACTER SET latin COLLATE latin1_general_ci )
DEFAULT CHARACTER SET hebrew COLLATE hebrew_general_ci;

?????????????????§µ???

SELECT *
FROM mytable
ORDER BY col COLLATE latin1_general_ci;

??????

MySQL ?????????????? mysql ?????????§³?

USE mysql;
SELECT user FROM user;

???????

CREATE USER myuser IDENTIFIED BY 'mypassword';

??????????????¦Ê?????

????????

RENAME myuser TO newuser;

??????

DROP USER myuser;

?????

SHOW GRANTS FOR myuser;

????? username@host ????????ÈÉusername@% ?????????????????

???????

GRANT SELECT, INSERT ON mydatabase.* TO myuser;

??????

REVOKE SELECT, INSERT ON mydatabase.* FROM myuser;

GRANT ?? REVOKE ??????????????????????

  • ??????????????? GRANT ALL?? REVOKE ALL??
  • ???????????? ON database.*??
  • ????????? ON database.table??
  • ??????§µ?
  • ?????›¥?????

????????

??????? Password() ????

SET PASSWROD FOR myuser = Password('newpassword');