MySQL JOIN & UNIONJamshid HashimiTrainer, Cresco Solutionhttp://firstname.lastname@example.org@jamshidhashimiajamshidhashimiAfghanistan WorkforceDevelopment Program
Agenda• Subqueries• Table Aliases• Multi-table Joins• UNION ALL• UNION Rules• GROUP BY
Subquery• A subquery is a SELECT statement within anotherstatement.• They allow queries that are structured so that it is possibleto isolate each part of a statement.• They provide alternative ways to perform operations thatwould otherwise require complex joins and unions.• Many people find subqueries more readable than complexjoins or unions. Indeed, it was the innovation of subqueriesthat gave people the original idea of calling the early SQL“Structured Query Language.”SELECT * FROM t1 WHERE column1 = (SELECTcolumn1 FROM t2);
Subquery• A subquery can return a scalar (a singlevalue), a single row, a single column, or a table(one or more rows of one or more columns).• In MySQL, you cannot modify a table andselect from the same table in a subquery. Thisapplies to statements such asDELETE, INSERT, REPLACE, UPDATE.
Subquery• EXISTS or NOT EXISTS– If a subquery returns any rows at all, EXISTSsubquery is TRUE, and NOT EXISTS subquery isFALSE.SELECT column1 FROM t1 WHERE EXISTS (SELECT* FROM t2);
Table Aliases• SQL aliases are used to give a databasetable, or a column in a table, a temporarilyname.• Basically aliases are created to make columnnames more readable.SELECT column_name AS alias_nameFROM table_name;
MySQL JOIN• “JOIN” is an SQL keyword used to query datafrom two or more related tables.• The act of joining in MySQL refers to smashingtwo or more tables into a single table.
INNER JOIN• The most frequently used clause is INNERJOIN. This produces a set of records whichmatch in both the joined tables, i.e. all userswho are enrolled on a course:SELECT user.name, user.courseFROM userINNER JOIN course ON course.id=user.course;
LEFT JOIN• If we do a LEFT JOIN, we get all records thatmatch in the same way and IN ADDITION weget an extra record for each unmatched recordin the left table of the join.SELECT user.name, user.courseFROM userLEFT JOIN course ON course.id=user.course;
RIGHT JOIN• A RIGHT JOIN produces a set of records whichmatches every entry in the right tableregardless of any matching entry in the lefttable.SELECT user.name, course.nameFROM userRIGHT JOIN course ON course.id=user.course;
UNION• You can use UNION if you want to select rowsone after the other from several tables, orseveral sets of rows from a single table all as asingle result set.• SyntaxSELECT ...UNION [ALL | DISTINCT] SELECT ...[UNION [ALL | DISTINCT] SELECT ...]
UNION• MySQL uses the names of columns in the firstSELECT statement as the labels for the output.SELECT fname, lname, addr FROM prospectUNIONSELECT first_name, last_name, address FROMcustomerUNIONSELECT company, , street FROM vendor;
UNION• MySQL UNION with ORDER BY– If you want to sort the results returned from thequery using the UNION operator, you need to useORDER BY clause in the last SQL SELECTstatement. You can put each SELECT statement inthe parentheses and use the ORDER BY clause asthe last statement.(SELECT customerNumber id,contactLastname nameFROM customers)UNION(SELECT employeeNumber id,firstname nameFROM employees)ORDER BY name,id
UNION Rules• The number and the order of the columnsmust be the same in all queries.• The data types must be compatible.• The columns selected in the different SELECTstatements must be in the same order
GROUP BY• The most common types of aggregatefunctions let you find out things like theminimum, maximum and even the average ofa "grouped" set of data. The trick tounderstanding aggregate functions is oftenunderstanding what kind of data is beinggrouped and analyzed.SELECT type, MIN(price) FROM products GROUP BY type
GROUP BY• Group BY is good for retrieving information abouta group of data. If you only had one product ofeach type, then GROUP BY would not be all thatuseful.• GROUP BY only shines when you have manysimilar things. For example, if you have a numberof products of the same type, and you want tofind out some statistical information like theminimum, maximum, or other top-level info, youwould use GROUP BY.