sql >> Database teknologi >  >> RDS >> Mysql

Tilslut tabeller med SUM-problem i MYSQL

Når du bruger flere joinforbindelser i hovedforespørgslen, ender du med et krydsprodukt af alle tabellerne, så summerne bliver ganget med antallet af rækker, der matcher i en anden tabel. Du skal flytte beløbene til underforespørgsler.

SELECT last_name, first_name, DATE_FORMAT(LEAST(mil_date, tm_date),  '%m/%d/%y' ) AS dates, 
        total, minutes
FROM bhds_teachers AS i
LEFT JOIN (
    SELECT ds_id, YEARWEEK(mil_date) AS week, MIN(mil_date) AS mil_date, SUM(drive_time) AS minutes
    FROM bhds_mileage
    WHERE mil_date BETWEEN '2016-04-11' AND  '2016-04-30'
    AND bhds_mileage.ds_id = 5
    GROUP BY ds_id, week) AS m 
ON m.ds_id = i.ds_id
LEFT JOIN (
    SELECT ds_id, YEARWEEK(tm_date) AS week, MIN(tm_date) AS tm_date, SUM(tm_hours) AS total
    WHERE tm_date BETWEEN '2016-04-11' AND '2016-04-30' AND bhds_timecard.ds_id = 5
    GROUP BY ds_id, week) AS t 
ON t.ds_id = i.ds_id AND t.week = m.week


  1. bedste måde at konvertere og validere en datostreng

  2. Sådan finder du duplikerede poster i MySQL

  3. Strømafbrydelser med EMCLI

  4. SQL Server Agent-advarsler