MySQL - union / join / json

ever.dยท2022๋…„ 11์›” 15์ผ
0

STUDY

๋ชฉ๋ก ๋ณด๊ธฐ
5/7

union ๐Ÿ‹

์„œ๋กœ ๋‹ค๋ฅธ ํ…Œ์ด๋ธ”์˜ ์ •๋ณด๋ฅผ ํ•˜๋‚˜๋กœ ํ•ฉ์ณ์„œ ๋ณด์—ฌ์ค€๋‹ค.
ex) a class ๋ผ๋Š” ํ…Œ์ด๋ธ”๊ณผ b class๋ผ๋Š” ํ…Œ์ด๋ธ”์ด ๋‚˜๋‰˜์–ด์ ธ ์žˆ๋Š”๋ฐ ์ด ๋‘ ํ…Œ์ด๋ธ”์— ๋‹ด๊ธด
๋ชจ๋“  ํ•™์ƒ๋“ค์˜ ์ •๋ณด๋ฅผ ํ•˜๋‚˜๋กœ ๋ณด์—ฌ์ฃผ๊ณ  ์‹ถ์„ ๋•Œ ํ•ด๋‹น ๊ธฐ๋Šฅ์„ ์“ธ ์ˆ˜ ์žˆ๋‹ค.
union์€ ์ค‘๋ณต๋˜๋Š” ๊ฐ’์„ ์ œ๊ฑฐํ•˜๊ณ  ๋ณด์—ฌ์ฃผ๋Š”๋ฐ์— ๋ฐ˜ํ•ด union all์€ ์ค‘๋ณต ๊ฐ’๊นŒ์ง€ ํฌํ•จํ•˜์—ฌ ๋ณด์—ฌ์ค€๋‹ค.

SELECT id, name, age
FROM a_class_students
where id = '123'
union
select id, name, age
from b_class_students
where id ='123'
order by updated_date desc

select ๋’ค์— ์˜ค๋Š” ์ปฌ๋Ÿผ๋ช…๊ณผ ์ปฌ๋Ÿผ ๊ฐœ์ˆ˜๋Š” ๋™์ผํ•ด์•ผ ํ•œ๋‹ค. ๋งŒ์•ฝ ์ปฌ๋Ÿผ๋ช…์ด ๋‹ค๋ฅด๋ฉด user_id as id ๋“ฑ์˜ ๋ณ„์นญ์„ ์ฃผ์–ด ๋งž์ถฐ์ค€๋‹ค. where์ ˆ ๋ฐ order by ์ดํ•˜์˜ ์กฐ๊ฑด์€ ์„ ํƒ์ด๋‹ค.


join ๐Ÿฑ

  • left join์„ ์“ธ ๋•Œ์—๋Š” group_by๋ฅผ ๋ถ™์—ฌ์„œ ์ค‘๋ณต๋˜๋Š” ๊ฐ’์„ ์ œ๊ฑฐํ•œ๋‹ค.

  • group by (์กฐ๊ฑด)์— ๋”ฐ๋ฅธ ๊ฒฐ๊ณผ ๊ฐ’์„ ํ•ฉgroup_concat์„ ์“ฐ๋ฉด ์œ ์šฉํ•˜๋‹ค.
    group_concat(๊ฒฐ๊ณผ column) from table_name group by (์กฐ๊ฑด column)

table : old_school

classstudent_name
Aํ™๊ธธ๋™
A์ž„๊บฝ์ •
Aํ™ฉ์ง„์ด

select class, group_concat(student_name) from old_school group by (class)

classstudent_name
Aํ™๊ธธ๋™, ์ž„๊บฝ์ •, ํ™ฉ์ง„์ด

group_concat(name separator '+') => + ๋ฅผ ๊ธฐ์ค€์œผ๋กœ ๋ถ„๋ฆฌ. (๊ตฌ๋ถ„์ž)

classstudent_name
Aํ™๊ธธ๋™ + ์ž„๊บฝ์ • + ํ™ฉ์ง„์ด

json ๐Ÿ‘พ

mysql์—์„œ json ๊ฐ’์„ ์ฝ๊ณ , ๋„ฃ๋Š” ๋ฐฉ๋ฒ•

  1. json ๊ฐ’ ์ฝ๊ธฐ
  • depth๋งŒ ์ž˜ ์ฐพ์•„๊ฐ€๋ฉด ๋œ๋‹ค.

select JSON_EXTRACT(ํ…Œ์ด๋ธ”๋ช….์ปฌ๋Ÿผ๋ช…,'$.key[*].value.key.value....') from ํ…Œ์ด๋ธ”๋ช…;

์˜ˆ๋ฅผ ๋“ค๋ฉด ์•„๋ž˜์—์„œ a_price์˜ count ๊ฐ’์ธ 1์„ ์–ป๊ณ  ์‹ถ๋‹ค๊ณ  ํ–ˆ์„ ๋•Œ

select JSON_EXTRACT(brand_table.information,'$.price[*].a_price.count') as a_price_count from brand_table;

table ๋ช… : brand_table

brandinformation
brand A{"price": [{"number": {"count": 0}, "a_price": {"count": 1}, "b_price": {"count": 2},"d_price"], "brand_logo": "lotte"}]}
  1. json ๊ฐ’ ์‚ฝ์ž… (insert)
  • ํ…Œ์ด๋ธ” ์ƒ์„ฑ

    create table class (name varchar(20), student_profile json)
    gp.price,'$.price_info[*].msrp_price.value'

  • 'key','value' ํ˜•์‹์œผ๋กœ insert

    insert into class(name, student_profile) values('ํ™๊ธธ๋™', json_object(
    'age', 10,
    'gender', 'man',
    'grade', 'B+'
    ));

  • select * from class;

classstudent_name
ํ™๊ธธ๋™{"age": 10, "grade": "B+", "gender": "man"}
profile
developer / not moving for fortune, only aiming for clear sense of purpose. That's all.

0๊ฐœ์˜ ๋Œ“๊ธ€