PostgreSQL基礎整理(一)

來源:互聯網
上載者:User

標籤:

1. 建立資料庫:
  1)登入bin目錄,createdb.exe -U postgres -e mydb;
  -U 表示本次操作的登入使用者名稱,如果不寫會取windows登入的賬戶,如Administrator;會提示無建立許可權;

2. 登入資料庫:
  1)用postgre內建的sql shell,登入時選擇資料庫為建立庫

3. CRUD
  書寫習慣:SQL語句大寫,其他小寫
  3.1)建立表:
    CREATE TABLE users( username char(20) PRIMARY KEY, password char(20));
  3.2) 插入資料:
    INSERT INTO users(username, password) VALUES(‘fredric‘,‘fredric‘),(‘sinny‘,‘sinny‘);
  3.4) 查詢資料:
    SELECT * FROM users;
  3.5) 刪除資料:

    DELETE FROM users WHERE username = "fredric";

4. JOIN
  準備:
  CREATE TABLE clubs(clubname char(20) PRIMARY KEY, note text);
  CREATE TABLE customers( username char(20) PRIMARY KEY, clubname char(20),FOREIGN KEY(clubname) REFERENCES clubs(clubname));

  INSERT INTO clubs(clubname, note) VALUES(‘myclub‘,‘good clubs‘);
  INSERT INTO clubs(clubname, note) VALUES(‘myclub1‘,‘good clubs‘);
  INSERT INTO customers(username, clubname) VALUES(‘fredric‘, ‘myclub‘);

  4.1) INNER JOIN
    SELECT * FROM clubs INNER JOIN customers ON clubs.clubname = customers.clubname;
    返回資料 myclub
  4.2) OUTTER JOIN(例如 LEFT JOIN)
    SELECT * FROM clubs LEFT JOIN customers ON clubs.clubname = customers.clubname;
  返回資料 myclub 和 myclub1

5. 索引
  5.1) 建立索引
    CREATE INDEX clubs_index ON clubs USING hash(clubname);
    CREATE INDEX clubs_index ON clubs USING btree(clubname);//B樹類型的索引支援多欄位
    CREATE UNIQUE INDEX clubs_index ON clubs;//唯一索引,postgre預設在主鍵上產生唯一索引
  5.2) 刪除索引
    DROP INDEX clubs_index;

6. 彙總函式
  6.1) COUNT
    SELECT COUNT(*) FROM clubs;
  6.2) MIN/MAX
    SELECT MIN(clubname) FROM clubs; //輸出myclub
    SELECT MAX(clubname) FROM clubs; //輸出myclub1

7. GROUP BY
  SELECT * FROM clubs GROUP By(clubname);
  SELECT COUNT(*) FROM clubs GROUP By(note);//1,2
  SELECT COUNT(*) FROM clubs GROUP By(note) HAVING COUNT(*) > 1;//2
  備忘:SQL執行順序 FROM -> WHERE -> 彙總函式-> GROUP BY -> HAVING -> ORDER BY -> SELECT;

8. 事務
  BEGIN TRANSACTION;
  DELETE FROM customers WHERE clubname = ‘myclub‘;
  DELETE FROM clubs WHERE clubname = ‘myclub‘;
  COMMIT; //執行刪除
  ROLLBACK; //復原操作

  SAVEPOINT;為儲存點,復原的位置
  例如:
    SAVEPOINT mypoint;
    ROLLBACK TO mypoint;

PostgreSQL基礎整理(一)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.