Join tables with SUM issue in MYSQL

When you use multiple joins in the main query, you end up with a cross product of all the tables, so the sums get multiplied by the number of rows matching in another table. You need to move the sums into subqueries. SELECT last_name, first_name, DATE_FORMAT(LEAST(mil_date, tm_date), ‘%m/%d/%y’ ) AS dates, total, minutes FROM bhds_teachers … Read more

SQL join: selecting the last records in a one-to-many relationship

This is an example of the greatest-n-per-group problem that has appeared regularly on StackOverflow. Here’s how I usually recommend solving it: SELECT c.*, p1.* FROM customer c JOIN purchase p1 ON (c.id = p1.customer_id) LEFT OUTER JOIN purchase p2 ON (c.id = p2.customer_id AND (p1.date < p2.date OR (p1.date = p2.date AND p1.id < p2.id))) … Read more

1052: Column ‘id’ in field list is ambiguous

SQL supports qualifying a column by prefixing the reference with either the full table name: SELECT tbl_names.id, tbl_section.id, name, section FROM tbl_names JOIN tbl_section ON tbl_section.id = tbl_names.id …or a table alias: SELECT n.id, s.id, n.name, s.section FROM tbl_names n JOIN tbl_section s ON s.id = n.id The table alias is the recommended approach — … Read more