UDEMY - The Ultimate MySQL Bootca…The Ultimate MySQL Bootcamp: Go from SQL Beginner to Expert를 수강하며 정리한 글
전 글에 이어서, 만약 pages가 가장 Max인 책의 title을 알고싶을 때는 어떻게 해야할까?
다양한 방법들을 시도해보았다.
mysql> SELECT MAX(pages), title FROM books;
ERROR 1140 (42000): In aggregated query without GROUP BY, expression #2 of SELECT list contains nonaggregated column 'book_shop.books.title'; this is incompatible with sql_mode=only_full_group_by
mysql> SELECT title, MAX(pages) FROM books WHERE pages = MAX(pages);
ERROR 1111 (HY000): Invalid use of group function
mysql> SELECT MAX(pages), title FROM books GROUP BY pages;
ERROR 1055 (42000): Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'book_shop.books.title' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
하지만 위 방법들 모두 에러를 뱉어냈다.
mysql> SELECT * FROM books WHERE pages = (SELECT MAX(pages) FROM books);
+---------+-------------------------------------------+--------------+--------------+---------------+----------------+-------+
| book_id | title | author_fname | author_lname | released_year | stock_quantity | pages |
+---------+-------------------------------------------+--------------+--------------+---------------+----------------+-------+
| 7 | The Amazing Adventures of Kavalier & Clay | Michael | Chabon | 2000 | 68 | 634 |
+---------+-------------------------------------------+--------------+--------------+---------------+----------------+-------+
1 row in set (0.00 sec)
page와 title만 보고싶다면 이렇게
mysql> SELECT title, pages FROM books WHERE pages = (SELECT MAX(pages) FROM books);
+-------------------------------------------+-------+
| title | pages |
+-------------------------------------------+-------+
| The Amazing Adventures of Kavalier & Clay | 634 |
+-------------------------------------------+-------+
1 row in set (0.00 sec)
하지만 서브쿼리의 단점이 있다. 각 쿼리가 따로 돌아가기 때문에 속도가 느리다. 지금 단계에서는 데이터가 적기 때문에 괜찮지만 나중에 속도의 차이가 생길 수 있다.
ORDER BY
와 LIMIT
을 이용mysql> SELECT * FROM books ORDER BY pages DESC LIMIT 1;
+---------+-------------------------------------------+--------------+--------------+---------------+----------------+-------+
| book_id | title | author_fname | author_lname | released_year | stock_quantity | pages |
+---------+-------------------------------------------+--------------+--------------+---------------+----------------+-------+
| 7 | The Amazing Adventures of Kavalier & Clay | Michael | Chabon | 2000 | 68 | 634 |
+---------+-------------------------------------------+--------------+--------------+---------------+----------------+-------+
1 row in set (0.00 sec)
mysql> SELECT title, pages FROM books ORDER BY pages DESC LIMIT 1;
+-------------------------------------------+-------+
| title | pages |
+-------------------------------------------+-------+
| The Amazing Adventures of Kavalier & Clay | 634 |
+-------------------------------------------+-------+
1 row in set (0.00 sec)
와우 이런방법이... 개발자들은 정말 천재들같다...