3 S Q L A n t i p a t t e r n s Trees/intro/parent.sql CREATE TABLE Comments ( comment_id SERIAL PRIMARY KEY, parent_id BIGINT UNSIGNED, comment TEXT

Similar documents
untitled

10.ppt

@OneToOne(cascade = = "addr_id") private Addr addr; public Emp(String ename, Addr addr) { this.ename = ename; this.a

13주-14주proc.PDF

5장 SQL 언어 Part II

강의 개요

I T C o t e n s P r o v i d e r h t t p : / / w w w. h a n b i t b o o k. c o. k r

목차 BUG 문법에맞지않는질의문수행시, 에러메시지에질의문의일부만보여주는문제를수정합니다... 3 BUG ROUND, TRUNC 함수에서 DATE 포맷 IW 를추가지원합니다... 5 BUG ROLLUP/CUBE 절을포함하는질의는 SUBQUE

단답형 (26 회기출문제 ) 1. 아래와같은테이블이있을때아래의 SQL 결과에대해서 Oracle, SQL Server 순서로적으시오 TAB1 COL1 CHAR(10) COL2 CHAR(10) INSERT INTO TAB1 VALUES ('1',''); INSERT INT

snu.pdf

199

b

Ç¥Áö

TITLE

구축환경 OS : Windows 7 그외 OS 의경우교재 p26-40 참조 Windows 의다른버전은조금다르게나타날수있음 Browser : Google Chrome 다른브라우저를사용해도별차이없으나추후수업의모든과정은크롬사용 한

90

RDB개요.ppt

DBMS & SQL Server Installation Database Laboratory

sms_SQL.hwp

Spring Boot/JDBC JdbcTemplate/CRUD 예제

PowerPoint 프레젠테이션

MySQL-Ch10

UNIST_교원 홈페이지 관리자_Manual_V1.0

歯sql_tuning2

목차 BUG DEQUEUE 의 WAIT TIME 이 1 초미만인경우, 설정한시간만큼대기하지않는문제가있습니다... 3 BUG [qp-select-pvo] group by 표현식에있는컬럼을참조하는집합연산이존재하지않으면결괏값오류가발생할수있습니다... 4

MS-SQL SERVER 대비 기능

(Humphery Kim) RAD Studio : h=p://tech.devgear.co.kr/ : h=p://blog.hjf.pe.kr/ Facebook : h=p://d.com/hjfactory :

8 장데이터베이스 8.1 기본개념 - 데이터베이스 : 데이터를조직적으로구조화한집합 (cf. 엑셀파일 ) - 테이블 : 데이터의기록형식 (cf. 엑셀시트의첫줄 ) - 필드 : 같은종류의데이터 (cf. 엑셀시트의각칸 ) - 레코드 : 데이터내용 (cf. 엑셀시트의한줄 )

NoSQL

PowerPoint 프레젠테이션

ALTIBASE HDB Patch Notes

Microsoft Word - Software Project Database Design_ver1.01_.docx

다양한 예제로 쉽게 배우는 오라클 SQL 과 PL/SQL

Connection 8 22 UniSQLConnection / / 9 3 UniSQL OID SET

Data Sync Manager(DSM) Example Guide Data Sync Manager (DSM) Example Guide DSM Copyright 2003 Ari System, Inc. All Rights reserved. Data Sync Manager

MySQL-Ch05

201502IC1AP-1 DB 구축 2015 학년도 2 학기 프로젝트특강보고서 프로젝트명 : DB 구축 ( DB ) 2015 년 11 월 20 일 지도교수 : 황치곤교수님 학과 : 정보통신공학과 1팀제출자 : 역할성명학번 조장 조재석 조원 송찬호 2

ALTIBASE HDB Patch Notes

06/09-101È£ä263»Áö

04/07-08(È£ä263»Áö

Remote UI Guide

6장. SQL

Microsoft PowerPoint - 10Àå.ppt

ETL_project_best_practice1.ppt

SQL Tuning Business Development DB

Microsoft PowerPoint - QVIZMVUMWURI.pptx

PRO1_09E [읽기 전용]

Microsoft PowerPoint Python-DB

PowerPoint 프레젠테이션

untitled

MySQL-.. 1

**Monster 3D

Spring Data JPA Many To Many 양방향 관계 예제

슬라이드 제목 없음

빅데이터 분산 컴퓨팅 -6

Relational Model

SQL

슬라이드 제목 없음

(......).hwp


1 데이터베이스 2 MySQL 설치 3 기초 SQL 4 고급 SQL 유용한함수들 JOIN inseog Kim Dep. of Applied Statistics, Dongguk통계데이터베이스 University jinseog.kim gma

제목 레이아웃

<C1DFB0B3BBE7B9FD3128B9FDB7C92C20B0B3C1A4B9DDBFB5292E687770>

윈도우시스템프로그래밍

PowerSHAPE 따라하기 Calculate 버튼을 클릭한다. Close 버튼을 눌러 미러 릴리프 페이지를 닫는다. D 화면을 보기 위하여 F 키를 누른다. - 모델이 다음과 같이 보이게 될 것이다. 열매 만들기 Shape Editor를 이용하여 열매를 만들어 보도록

1217 WebTrafMon II

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션

Microsoft Word - [Unioneinc] 특정컬럼의 통계정보 갱신_ _ldh.doc

교육2 ? 그림

배치프로그램에서튜닝대상 SQL 추출하기 엑셈컨설팅본부 /DB 컨설팅팀박성호 배치프로그램의성능문제를진단하기위해트레이스를사용할수없고, 개별 SQL 에대한성 능점검은비효율적인경우에어떻게배치프로그램의성능문제를제대로파악하고개선안을도 출할것인가? 복잡한로직을가지고있는프로그램 (

다양한 예제로 쉽게 배우는 오라클 SQL 과 PL/SQL

Jerry Held


강의 개요

01

PowerPoint Presentation

PowerPoint Presentation

FileMaker ODBC 및 JDBC 가이드

01_피부과Part-01

관광스토리텔링2_내지

윈도우시스템프로그래밍

InsertColumnNonNullableError(#colName) 에해당하는메시지출력 존재하지않는컬럼에값을삽입하려고할경우, InsertColumnExistenceError(#colName) 에해당하는메시지출력 실행결과가 primary key 제약에위배된다면, Ins

untitled

소프트웨어개발방법론

06년팜플렛직접하리용

歯PLSQL10.PDF

객관식 1. 아래의쿼리를만족하는결과를가장잘설명한것은? SELECT A.* FROM HR.EMPLOYEES A, HR.EMPLOYEES B WHERE 1=1 AND A.MANAGER_ID = B.EMPLOYEE_ID AND B.SALARY >= ANY A.SALARY;

JTS 1-2¿ùÈ£ ³»Áö_Ä÷¯ PDF¿ë

PHP & ASP

Microsoft PowerPoint - Chap5 [호환 모드]

K&R2 Reference Manual 번역본

WINDOW FUNCTION 의이해와활용방법 엑셈컨설팅본부 / DB 컨설팅팀정동기 개요 Window Function 이란행과행간의관계를쉽게정의할수있도록만든함수이다. 윈도우함수를활용하면복잡한 SQL 들을하나의 SQL 문장으로변경할수있으며반복적으로 ACCESS 하는비효율역

(Asynchronous Mode) ( 1, 5~8, 1~2) & (Parity) 1 ; * S erial Port (BIOS INT 14H) - 1 -

thesis

Database Applications - 멀티미디어 데이터베이스 – 제6장 텍스트 색인과 검색

ePapyrus PDF Document

Microsoft Word - PLSQL.doc

ALTIBASE HDB Patch Notes

<443A5C4C C4B48555C B3E25C32C7D0B1E25CBCB3B0E8C7C1B7CEC1A7C6AE425CBED0C3E0C7C1B7CEB1D7B7A55C D616E2E637070>

Transcription:

3 S Q L A n t i p a t t e r n s Trees/intro/parent.sql CREATE TABLE Comments ( comment_id SERIAL PRIMARY KEY, parent_id BIGINT UNSIGNED, comment TEXT NOT NULL, FOREIGN KEY (parent_id) REFERENCES Comments(comment_id) );

3.1

3.2 Trees/anti/adjacency-list.sql CREATE TABLE Comments ( comment_id SERIAL PRIMARY KEY, parent_id BIGINT UNSIGNED, bug_id BIGINT UNSIGNED NOT NULL, author BIGINT UNSIGNED NOT NULL, comment_date DATETIME NOT NULL, comment TEXT NOT NULL, FOREIGN KEY (parent_id) REFERENCES Comments(comment_id), FOREIGN KEY (bug_id) REFERENCES Bugs(bug_id), FOREIGN KEY (author) REFERENCES Accounts(account_id) );

Trees/anti/parent.sql SELECT c1.*, c2.* FROM Comments c1 LEFT OUTER JOIN Comments c2 ON c2.parent_id = c1.comment_id;

Trees/anti/ancestors.sql SELECT c1.*, c2.*, c3.*, c4.* FROM Comments c1 -- 1 LEFT OUTER JOIN Comments c2 ON c2.parent_id = c1.comment_id -- 2 LEFT OUTER JOIN Comments c3 ON c3.parent_id = c2.comment_id -- 3 LEFT OUTER JOIN Comments c4 ON c4.parent_id = c3.comment_id; -- 4 Trees/anti/all-comments.sql SELECT * FROM Comments WHERE bug_id = 1234;

Trees/anti/insert.sql INSERT INTO Comments (bug_id, parent_id, author, comment) VALUES (1234, 7, Kukla, Thanks! ); Trees/anti/update.sql UPDATE Comments SET parent_id = 3 WHERE comment_id = 6; Trees/anti/delete-subtree.sql SELECT comment_id FROM Comments WHERE parent_id = 4; -- SELECT comment_id FROM Comments WHERE parent_id = 5; -- SELECT comment_id FROM Comments WHERE parent_id = 6; -- SELECT comment_id FROM Comments WHERE parent_id = 7; -- DELETE FROM Comments WHERE comment_id IN ( 7 ); DELETE FROM Comments WHERE comment_id IN ( 5, 6 ); DELETE FROM Comments WHERE comment_id = 4; Trees/anti/delete-non-left.sql SELECT parent_id FROM Comments WHERE comment_id = 6; -- UPDATE Comments SET parent_id = 4 WHERE parent_id = 6; DELETE FROM Comments WHERE comment_id = 6;

3.3

3.4

Trees/legit/cte.sql WITH CommentTree (comment_id, bug_id, parent_id, author, comment, depth) AS ( SELECT *, 0 AS depth FROM Comments WHERE parent_id IS NULL UNION ALL SELECT c.*, ct.depth+1 AS depth FROM CommentTree ct JOIN Comments c ON (ct.comment_id = c.parent_id) ) SELECT * FROM CommentTree WHERE bug_id = 1234; Trees/legit/connect-by.sql SELECT * FROM Comments START WITH comment_id = 9876 CONNECT BY PRIOR parent_id = comment_id; 3.5

Trees/soln/path-enum/create-table.sql CREATE TABLE Comments ( comment_id SERIAL PRIMARY KEY, path VARCHAR(1000), bug_id BIGINT UNSIGNED NOT NULL, author BIGINT UNSIGNED NOT NULL, comment_date DATETIME NOT NULL, comment TEXT NOT NULL, FOREIGN KEY (bug_id) REFERENCES Bugs(bug_id), FOREIGN KEY (author) REFERENCES Accounts(account_id) );

Trees/soln/path-enum/ancestors.sql SELECT * FROM Comments AS c WHERE 1/4/6/7/ LIKE c.path % ; Trees/soln/path-enum/descendants.sql SELECT * FROM Comments AS c WHERE c.path LIKE 1/4/ % ;

Trees/soln/path-enum/count.sql SELECT COUNT(*) FROM Comments AS c WHERE c.path LIKE 1/4/ % GROUP BY c.author; Trees/soln/path-enum/insert.sql INSERT INTO Comments (author, comment) VALUES ( Ollie, Good job! ); UPDATE Comments SET path = (SELECT path FROM Comments WHERE comment_id = 7) LAST_INSERT_ID() / WHERE comment_id = LAST_INSERT_ID();

Trees/soln/nested-sets/create-table.sql CREATE TABLE Comments ( comment_id SERIAL PRIMARY KEY, nsleft INTEGER NOT NULL, nsright INTEGER NOT NULL, bug_id BIGINT UNSIGNED NOT NULL, author BIGINT UNSIGNED NOT NULL, comment_date DATETIME NOT NULL, comment TEXT NOT NULL, FOREIGN KEY (bug_id) REFERENCES Bugs (bug_id), FOREIGN KEY (author) REFERENCES Accounts(account_id) );

Trees/soln/nested-sets/descendants.sql SELECT c2.* FROM Comments AS c1 JOIN Comments as c2 ON c2.nsleft BETWEEN c1.nsleft AND c1.nsright WHERE c1.comment_id = 4; Trees/soln/nested-sets/ancestors.sql SELECT c2.* FROM Comments AS c1 JOIN Comment AS c2 ON c1.nsleft BETWEEN c2.nsleft AND c2.nsright WHERE c1.comment_id = 6; Trees/soln/nested-sets/depth.sql -- depth = 3 SELECT c1.comment_id, COUNT(c2.comment_id) AS depth FROM Comment AS c1 JOIN Comment AS c2 ON c1.nsleft BETWEEN c2.nsleft AND c2.nsright WHERE c1.comment_id = 7 GROUP BY c1.comment_id;

DELETE FROM Comment WHERE comment_id = 6; -- depth = 2 SELECT c1.comment_id, COUNT(c2.comment_id) AS depth FROM Comment AS c1 JOIN Comment AS c2 ON c1.nsleft BETWEEN c2.nsleft AND c2.nsright WHERE c1.comment_id = 7 GROUP BY c1.comment_id; Trees/soln/nested-sets/parent.sql SELECT parent.* FROM Comment AS c JOIN Comment AS parent ON c.nsleft BETWEEN parent.nsleft AND parent.nsright LEFT OUTER JOIN Comment AS in_between ON c.nsleft BETWEEN in_between.nsleft AND in_between.nsright AND in_between.nsleft BETWEEN parent.nsleft AND parent.nsright WHERE c.comment_id = 6 AND in_between.comment_id IS NULL;

Trees/soln/nested-sets/insert.sql -- NS 8 9 UPDATE Comment SET nsleft = CASE WHEN nsleft >= 8 THEN nsleft+2 ELSE nsleft END, nsright = nsright+2 WHERE nsright >= 7; -- #5, NS 8, 9 INSERT INTO Comment (nsleft, nsright, author, comment) VALUES (8, 9, Fran, Me too! ); Trees/soln/closure-table/create-table.sql CREATE TABLE Comments ( comment_id SERIAL PRIMARY KEY, bug_id BIGINT UNSIGNED NOT NULL, author BIGINT UNSIGNED NOT NULL, comment_date DATETIME NOT NULL, comment TEXT NOT NULL, FOREIGN KEY (bug_id) REFERENCES Bugs(bug_id), FOREIGN KEY (author) REFERENCES Accounts(account_id) );

CREATE TABLE TreePaths ( ancestor BIGINT UNSIGNED NOT NULL, descendant BIGINT UNSIGNED NOT NULL, PRIMARY KEY(ancestor, descendant), FOREIGN KEY (ancestor) REFERENCES Comments(comment_id), FOREIGN KEY (descendant) REFERENCES Comments(comment_id) ); Trees/soln/closure-table/descendants.sql SELECT c.* FROM Comments AS c JOIN TreePaths AS t ON c.comment_id = t.descendant WHERE t.ancestor = 4;

Trees/soln/closure-table/ancestors.sql SELECT c.* FROM Comments AS c JOIN TreePaths AS t ON c.comment_id = t.ancestor WHERE t.descendant = 6;

Trees/soln/closure-table/insert.sql INSERT INTO TreePaths (ancestor, descendant) SELECT t.ancestor, 8 FROM TreePaths AS t WHERE t.descendant = 5 UNION ALL SELECT 8, 8; Trees/soln/closure-table/delete-left.sql DELETE FROM TreePaths WHERE descendant = 7; Trees/soln/closure-table/delete-subtree.sql DELETE FROM TreePaths WHERE descendant IN (SELECT descendant WHERE descendant IN (FROM TreePaths WHERE descendant IN (WHERE ancestor = 4);

Trees/soln/closure-table/move-subtree.sql DELETE FROM TreePaths WHERE descendant IN (SELECT descendant WHERE descendant IN (FROM TreePaths WHERE descendant IN (WHERE ancestor = 6) AND ancestor IN (SELECT ancestor AND ancestor IN (FROM TreePaths AND ancestor IN (WHERE descendant = 6 AND ancestor IN (AND ancestor!= descendant); Trees/soln/closure-table/move-subtree.sql INSERT INTO TreePaths (ancestor, descendant) SELECT supertree.ancestor, subtree.descendant FROM TreePaths AS supertree CROSS JOIN TreePaths AS subtree WHERE supertree.descendant = 3 AND subtree.ancestor = 6;

Trees/soln/closure-table/child.sql SELECT * FROM TreePaths WHERE ancestor = 4 AND path_length = 1;

SQL Antipatterns Tip