테이블 하나의 값을 바꿔치기하는데 특정 조건에 맞게 넣는방법

근데.. 특이하게도.. postgresql에서 순서가 뒤죽박죽이 된다..

recored가 원래 1부터 100까지 순서대로 나왔는데

update table set colname = 

case when condition then val1;

end;

이렇게 돌리니

 

뒤죽박죽으로 나온다. 실행 정책인가?

 

[링크 : https://blog.naver.com/50after/220930638267]

Posted by 구차니

말은 거창한데..

sequence나 mysql 기준 auto increment 지정된 Pk 값을 나중에 추가해서

그 값을 넣어줄때 쓰는 방법

UPDATE table SET column = nextval('seq_name') 하면 해결!

 

정말.. SQL 문이 강력하구나.. 라는걸 느끼는 중

 

UPDATE property_pictures SET id=10000+nextval('property_gallery_id_seq');

[링크 : https://fle.github.io/reset-a-postgresql-sequence-and-recompute-column-values.html]

'프로그램 사용 > postgreSQL' 카테고리의 다른 글

postgresql where similar to (정규표현식)  (0) 2019.09.29
update case  (0) 2019.09.26
sql group by like?  (0) 2019.09.25
postgresql select having  (0) 2019.09.24
postgresql select from , (cross join)  (0) 2019.09.24
Posted by 구차니

문법은 미지원

유사하게 case로 구현은 가능하나

추후 값에 따라 자동으로 유사한것 끼리 묶는건 불가능 할 듯

 

[링크 : https://stackoverflow.com/questions/6101404/sql-group-by-like]

Posted by 구차니

having 은 조건에 만족하지 않는 그룹 rows를 제거한다. HAVING은 WHERE과는 다르다: WHERE는 GROUP BY의 적용 전에 개별 rows를 필터하는 대신 HAVING는 GROUP BY에 의해 생성된 group rows를 필터한다.

(해석은 하는데 무슨 뜻이여...

일단은 생성하고 나서 하나하나 생성하냐, 아니면 그룹으로 묶이는 애들 레벨에서 미리 처리하냐 차이인가?)

HAVING Clause

The optional HAVING clause has the general form

where condition is the same as specified for the WHERE clause.

HAVING eliminates group rows that do not satisfy the condition. HAVING is different from WHERE: WHERE filters individual rows before the application of GROUP BY, while HAVING filters group rows created by GROUP BY. Each column referenced in condition must unambiguously reference a grouping column, unless the reference appears within an aggregate function or the ungrouped column is functionally dependent on the grouping columns.

The presence of HAVING turns a query into a grouped query even if there is no GROUP BY clause. This is the same as what happens when the query contains aggregate functions but no GROUP BY clause. All the selected rows are considered to form a single group, and the SELECT list and HAVING clause can only reference table columns from within aggregate functions. Such a query will emit a single row if the HAVING condition is true, zero rows if it is not true.

Currently, FOR NO KEY UPDATE, FOR UPDATE, FOR SHARE and FOR KEY SHARE cannot be specified with HAVING.

[링크 : https://www.postgresql.org/docs/9.5/sql-select.html]

Posted by 구차니

mysql 쪽에서는 당연히 쓰는거긴 한데.. postgresql 에서도 , 로 list를 적어 주면

자동으로 cartesian product(cross join)으로 결과를 내준다고 한다.

갑자기 cross join이 inner join인지 헷갈리네...

FROM Clause

The FROM clause specifies one or more source tables for the SELECT. If multiple sources are specified, the result is the Cartesian product (cross join) of all the sources. But usually qualification conditions are added (via WHERE) to restrict the returned rows to a small subset of the Cartesian product.

[링크 : https://www.postgresql.org/docs/9.5/sql-select.html#SQL-FROM]

 

 

+

inner join과 cross join은 다른듯

join_type

One of

  • [ INNER ] JOIN

  • LEFT [ OUTER ] JOIN

  • RIGHT [ OUTER ] JOIN

  • FULL [ OUTER ] JOIN

  • CROSS JOIN

[링크 :https://www.postgresql.org/docs/9.5/sql-select.html]

 

일단은.. cross join에 where를 주면 inner join이 되는건가? 좀 헷갈리네..

Join 종류

 설명

 Cross Join

 Outer Node 의 각 row 에 대해 Inner Node 의 모든 row가 결합되어 반환

 Inner Join

 Outer Node 의 각 row 에 대해 Inner Node 의 모든 row 중 Join 조건을 만족하는 row 에 대해서만 결합되어 반환

 Equi Join

 조건의 연산자가 = 인 경우
 Non Equi Join  조건의 연산자가 = 가 아닌 경우

[링크 : https://mozi.tistory.com/69]

'프로그램 사용 > postgreSQL' 카테고리의 다른 글

sql group by like?  (0) 2019.09.25
postgresql select having  (0) 2019.09.24
postgresql transaction begin / commit / rollback  (0) 2019.09.24
sql 문 계산하기  (0) 2019.09.24
string_agg() + COALESCE() + DISTINCT  (0) 2019.09.23
Posted by 구차니

BEGIN; 이 프로시저의 시작인줄 알았는데..

트랜잭션의 시작이었구나..

 

rollback을 위해서는 savepoint를 만들어 놔야하고

문제가 없으면 commit; 으로 transaction을 완료하면 된다.

BEGIN;
UPDATE accounts SET balance = balance - 100.00
    WHERE name = 'Alice';
SAVEPOINT my_savepoint;
UPDATE accounts SET balance = balance + 100.00
    WHERE name = 'Bob';
-- oops ... forget that and use Wally's account
ROLLBACK TO my_savepoint;
UPDATE accounts SET balance = balance + 100.00
    WHERE name = 'Wally';
COMMIT;

[링크 : https://www.postgresql.org/docs/8.3/tutorial-transactions.html]

 

근데.. 이렇게 하면 WAL 로 미친듯이 써질려나?

'프로그램 사용 > postgreSQL' 카테고리의 다른 글

postgresql select having  (0) 2019.09.24
postgresql select from , (cross join)  (0) 2019.09.24
sql 문 계산하기  (0) 2019.09.24
string_agg() + COALESCE() + DISTINCT  (0) 2019.09.23
join where와 on  (0) 2019.09.18
Posted by 구차니

값이 integer면 - 해서 계산해도 된다.

우옹.. 신기하당...

 

[링크 : https://blog.naver.com/kimnx9006/220573722518]

Posted by 구차니

아래와 같이 하면 값이 없는 애는 NULL로 표기된채로 ,로 여러개 쭈르르르륵 나온다.

NULL을 해주는 이유는 NULL일 경우 값을 아예 생략해서 몇개의 값을 합친건지 알수가 없기 때문.

어떻게 보면.. DB를 DB답게 안쓰는 방법인데

여러개의 레코드를 합치다 보면 NULL의 위치가 서로 다를테니 형식을 맞추기 위함이라고 해야하려나?

 

string_agg(COALESCE(합칠변수::text,'NULL'), ',')

---

 

ms sql server 에서는 isnull로 값없는건 빠지지 않도록 해주어야 한다고..

[링크 : https://docs.microsoft.com/ko-kr/sql/t-sql/functions/string-agg-transact-sql?view=sql-server-2017]

[링크 : https://xshine.tistory.com/205]

[링크 : https://dbrang.tistory.com/1289]

 

COALESCE() 라는 함수를 지원한다고.

[링크 : http://www.postgresqltutorial.com/postgresql-isnull/]

 

The COALESCE function returns the first of its arguments that is not null. Null is returned only if all arguments are null. It is often used to substitute a default value for null values when data is retrieved for display, for example:

This returns description if it is not null, otherwise short_description if it is not null, otherwise (none).

Like a CASE expression, COALESCE only evaluates the arguments that are needed to determine the result; that is, arguments to the right of the first non-null argument are not evaluated. This SQL-standard function provides capabilities similar to NVL and IFNULL, which are used in some other database systems.

[링크 : https://www.postgresql.org/docs/9.5/functions-conditional.html]

 

[링크 : https://stackoverflow.com/.../how-to-concatenate-strings-of-a-string-field-in-a-postgresql-group-by-query]

[링크 : https://blog.gaerae.com/2015/09/postgresql-multiple-rows-and-json-or-string.html]

 

2019/09/08 - [프로그램 사용/postgreSQL] - sql 여러행을 하나로 합치기 concat

 

+

json_agg(expr) 은 delimiter 없이 JSON ARRAY 타입으로 리턴해준다.

json_agg는 string_agg와는 다르게 null을 기본으로 출력해준다.

 

+

DISTINCT를 string_arr 안에서 사용이 가능하다.

[링크 : https://yahwang.github.io/posts/46]

'프로그램 사용 > postgreSQL' 카테고리의 다른 글

postgresql transaction begin / commit / rollback  (0) 2019.09.24
sql 문 계산하기  (0) 2019.09.24
join where와 on  (0) 2019.09.18
복수 컬럼에 대한 inner join  (0) 2019.09.18
postgresql update  (0) 2019.09.18
Posted by 구차니

WHERE는 JOIN에 붙는게 아니라 유사해 보이지만 다른 결과를 가져오니 주의가 필요해 보인다.

원래는 JOIN ... ON 으로 조건식을 해서 붙는 듯

 

[링크 : https://eddyplusit.tistory.com/52]

[링크 : https://blog.leocat.kr/notes/2017/07/28/sql-join-on-vs-where]

 

+

2019.09.24

inner join 에서는 where나 on이나 동일한건가?

[링크 : https://sarc.io/index.php/mariadb/1303-sql-join-on-where]

[링크 : http://www.sqler.com/bSQLQA/140801]

 

ON절에 조건을 주면, 테이블을 합칠 때 조건이 걸려서 하나의 가상테이블(join된 결과)이 만들어집니다. 그와 반대로 WHERE절에 조건이 걸리면, 다 만들어진 테이블을 다시 훑으면서 해당 조건에 맞는 결과물을 반환하는 게 됩니다. 이는 OUTER JOIN에서 확연하게 차이를 보입니다.

[링크 : https://viewa.tistory.com/44]

Posted by 구차니

1개 테이블에 다른 테이블의 값이 여러개 있어서

어떻게 한번에  join이 가능한지 보는데.. 별거 없네

JOIN ON에 여러개 붙이면 된다.

 

[링크 : https://stackoverflow.com/questions/26916741/how-to-join-two-tables-by-multiple-columns-in-sql/26916803]

'프로그램 사용 > postgreSQL' 카테고리의 다른 글

string_agg() + COALESCE() + DISTINCT  (0) 2019.09.23
join where와 on  (0) 2019.09.18
postgresql update  (0) 2019.09.18
postgresql 정수형에 "NULL"이 null로 인식을 못할때  (0) 2019.09.18
query tweak join vs large table  (0) 2019.09.17
Posted by 구차니