본문 바로가기

프로그래밍 언어/MySQL

[MySQL] 실습: 좋아요

반응형

-- insert 값 : https://yeo0616.tistory.com/121

 

테이블 설정 후에 차례대로 실행하는 것이 중요 (foreign key 설정 영향)

users 테이블 생성 및 설정 -> photos 테이블 -> follows 테이블 -> comments 테이블 -> likes 테이블 -> tags 테이블 -> photo_tags 테이블

 

use yh_db;

 

테이블명 컬럼
users id username created_at    
photos id image_url user_id created_at  
follows id follower_id followee_id created_at  
comments id user_id photo_id comment_text created_at
likes id user_id photo_id created_at  
tags id tag_name      
photo_tags id photo_id tag_id    

 

-- 1. 가장 오래된 회원 5명은 누구입니까

select * 
from users
order by created_at 
limit 5;

 

-- 2. 회원가입을 가장 많이 하는 요일은 무슨 요일이며, 몇명입니까?

select count(*) as cnt, dayname(created_at) as day
from users
group by day
order by count(*) desc;

 

-- 3. 회원가입은 했지만, 사진은 한번도 올리지 않는 유저들의 데이터를 가져오세요.

select u.username
from users u
left join photos p on u.id = p.user_id
where image_url is null;

 

-- 4. 가장 유명한 사진은 무엇인지 찾아서, 그 사진의 유저이름, image_url, 좋아요 수를 나타내세요.

select u.username, p.image_url, count(l.user_id) as likes
from photos p
join likes l on p.id = l.photo_id
join users u on u.id = p.user_id
group by p.image_url 
order by likes desc
limit 1;

 

-- 5. 가장 많이 사용된 해시태그의, tag_name과 몇개인지 조회하세요. 

select t.tag_name, count(*) as count
from photo_tags pt
join tags t
on pt.tag_id = t.id
group by t.tag_name
order by count desc;

 

-- 6. 좋아요를 80개 이상 한 사람들의 이름과 좋아요 수를 조회하세요. 

select count(l.user_id) as cnt,u.username
from likes l
join users u
on l.user_id = u.id
group by l.user_id
having count(l.user_id) >=80
order by cnt desc;

 

반응형