목록Database/MySQL (36)
군침이 싹 도는 코딩
select sum(pages) from books; # select sum(컬럼) 으로 사용한다
select count(*) from books; # select count(컬럼)을 사용한다 select count( distinct author_lname ) from books; # 유니크한 데이터를 구할때는 distinct 를 같이 사용해서 구할수있다
![](http://i1.daumcdn.net/thumb/C150x150/?fname=https://blog.kakaocdn.net/dn/baEbdP/btrS0dNTjpr/75SIlR2JiVev3HtBoAK8c1/img.png)
select author_lname, count( title ) as cnt from books group by author_lname ; # 코드블럭은 author_lname 으로 묶어서 author_lname 이 포함된 title 이 몇개냐라는 뜻 위치는 from 밑에 위치한다 group by 컬럼명을 사용한다 먼저 author_lname으로 묶어준다음 select 옆에 조건을 써준다 select released_year , avg(stock_quantity) as average from books group by released_year having average > 70; # group by 로 묶은 데이터들은 값을 비교하거나 할때 having 을 사용해줘야한다
![](http://i1.daumcdn.net/thumb/C150x150/?fname=https://blog.kakaocdn.net/dn/zkcF5/btrVIvX5JPL/2QVqFwuIMQVRDjuLCXy8AK/img.png)
select * from books where title like '%the%' ; # 위치는 from 밑에 위치하며 where 컬럼 like '%가져올 문자%' 순으로 입력하며 %의 위치에 따라 의미가 달라지는데 의미는 어떠한 문자라고 해석하면 된다 위 코드에는 양쪽 다 있으므로 the 를 포함한 모든 데이터도 다 가져오라는 뜻이고 왼쪽만 있다면 the 로 끝나는 데이터 오른쪽만 있다면 the로 시작하는 데이터를 가져오라는 뜻이된다 select * from books where stock_quantity like '__'; # 데이터의 자리수로 가져올수도 있는데 이때는 언더스코어 갯수로 표시해준다 가져올 자리수가 두자리이면 언더스코어 두개 이런식으로 써주면 된다 숫자나 문자 둘다 가능하다 # 마지막으로..
select * from books limit 0,5; # limit를 사용하며 from 밑에 위치해야한다 숫자가 두개라면 왼쪽이 시작위치 (offset) 이고 오른쪽이 갯수이다 select * from books order by released_year desc limit 0,7 ; # 해당 코드는 컬럼을 내림차순하고 7개의 데이터를 가져오라는 것인데 이때 순서가 중요하다 먼저 정렬한 뒤 마지막에 데이터를 끊어 가져온다
select * from books order by author_lname ; # order by 컬럼을 써주면 된다 이것의 위치는 from 밑에 위치해야한다 select book_id ,title, concat( author_fname ,' ', author_lname ) as full_name, released_year,stock_quantity,pages from books order by full_name ; # 정렬할때 as로 지정해준 컬럼명으로 사용해도 된다 select * from books order by author_lname desc , author_fname asc ; # 오름차순으로 정렬하고싶으면 아무것도 쓰지않거나 asc 를 쓰고 내림차순으로 정렬하고싶으면 desc 를 사용한다
select distinct author_lname from books; # select distinct 컬럼 순으로 쓴다 해당 컬럼의 유니크 데이터만 보여준다 select distinct concat( author_fname ,' ', author_lname ) as 'full name' from books; # distinct는 함수가 아니기때문에 괄호를 사용하지 않는다 다른 함수와 혼용할때도 마찬가지이다
select concat( substring(title,1,10), '...') as title from books; # 문자열을 다루는 함수를 여럿 섞어서도 사용이 가능하다 해당 코드블럭에서는 타이틀 컬럼을 첫번째부터 열번째자리까지 가져오고 뒤에 ... 이라는 문자를 붙이라는 뜻이다 select concat( substring(title,1,10), '...') as short_title, concat(author_fname,author_lname) as author, concat(stock_quantity,'in stock') as quantity from books; # 해당 코드블럭은 타이틀 컬럼을 첫번째부터 열번째까지 가져오고 뒤에 ... 을 붙이고 author_fname 과 l_name 컬럼을..