MySQL Basic Samples
This is the trace of my learning process.
DISTINCT and Arithmetics
SELECT DISTINCT CITY FROM STATION
WHERE ID % 2 = 0;
COUNT AND DISTINCT
SELECT COUNT(CITY)-COUNT(DISTINCT CITY) FROM STATION;
MIN and MAX
SELECT MAX(POPULATION)-MIN(POPULATION) FROM CITY;
ROUND and TRUNCATE
SELECT ROUND(1.298, 1), TRUNCATE(1.298, 1); # => 1.3 1.2
SELECT TRUNCATE(SUM(LAT_N), 4) FROM STATION
WHERE 38.7880 < LAT_N AND LAT_N < 137.2345;
ORDER BY and LIMIT
SELECT CITY, LENGTH(CITY) AS LEN FROM STATION
ORDER BY LEN, CITY
LIMIT 1;
SUBSTRING
Pattern Matchings
There are two different bodies of pattern matchings available in MySQL, namely standard SQL pattern matchings and the extended regular expressions. The standard one returns true if the whole string matches the pattern whereas the extended regular expressions return true if a part of the string matches the pattern.
Standard SQL Pattern Matchings
_
any single character%
an arbitrary number of characters- Use
LIKE
orNOT LIKE
instead of=
or<>
as a comparison operator
Extended Regular Expressions
.
matches any single character[abc]
matches a, b, or c*
matches zero or more instances of the patterns preceding it{n}
repeat the preceding pattern n-times^
and$
are used to anchor the pattern matching point to the beginning and the end
There are some ways to force the pattern to match case-sensitively.
Aggregations
Subqueries
SELECT ROUND(LONG_W,4)
FROM STATION
WHERE LAT_N = (SELECT MAX(LAT_N) FROM STATION WHERE LAT_N < 137.2345);
You HAVE TO name the table you made by a subquery.
SELECT TRUNCATE(SQRT(POW(C-A, 2)+POW(D-B, 2)), 4)
FROM (
SELECT MIN(LAT_N) AS A, MIN(LONG_W) AS B, MAX(LAT_N) AS C, MAX(LONG_W) AS D
FROM STATION
) AS _;
Joins
Joins make a new table from two tables.
- Inner Join: The new table consists of rows which successfully joined on the columns.
- Left Join: The new table consists of all the rows from the left table, part of which are extended with the rows from the right table.
- Right Join: The new table consists of all the rows from the right table, part of which are extended with the rows from the left table.
SELECT SUM(City.population)
FROM CITY
INNER JOIN COUNTRY
ON CITY.CountryCode = COUNTRY.Code
WHERE Country.Continent = "Asia";