MySQL JOIN & UNION

5,471 views

Published on

Published in: Technology, Career

MySQL JOIN & UNION

  1. 1. MySQL JOIN & UNIONJamshid HashimiTrainer, Cresco Solutionhttp://www.jamshidhashimi.comjamshid@netlinks.af@jamshidhashimiajamshidhashimiAfghanistan WorkforceDevelopment Program
  2. 2. Agenda• Subqueries• Table Aliases• Multi-table Joins• UNION ALL• UNION Rules• GROUP BY
  3. 3. 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);
  4. 4. 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.
  5. 5. 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);
  6. 6. 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;
  7. 7. 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.
  8. 8. 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;
  9. 9. 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;
  10. 10. 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;
  11. 11. 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 ...]
  12. 12. 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;
  13. 13. 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
  14. 14. 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
  15. 15. 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
  16. 16. 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.
  17. 17. QUESTIONS?

×