sql >> Database >  >> RDS >> Mysql

MySQL-aggregatiefuncties met LEFT JOIN

Aangezien je het filter hebt voor de notes tabel in de WHERE clausule de JOIN gedraagt ​​zich als een INNER JOIN , verplaats het naar de JOIN staat:

SELECT
  jobs.*,
  MAX(notes.`timestamp`) AS complete_date
FROM jobs
LEFT JOIN notes 
  ON (jobs.id=notes.job_id)
  AND (notes.type="complete" OR notes.type IS NULL)
WHERE (jobs.status="complete" OR jobs.status="closed")
GROUP BY jobs.id
ORDER BY complete_date ASC;

Dit kan ook worden gedaan met behulp van een subquery, dus u past het notitiefilter toe in de subquery:

SELECT
  jobs.*,
  n.complete_date
FROM jobs
LEFT JOIN
(
    select job_id, MAX(`timestamp`) AS complete_date
    from notes 
    where (type="complete" OR type IS NULL)
    group by job_id
) n
  ON (jobs.id=n.job_id)
WHERE (jobs.status="complete" OR jobs.status="closed")
ORDER BY complete_date ASC



  1. Draaien in Oracle 11g

  2. LAST_INSERT_ID() retourneert altijd 0 (RMySQL) - afzonderlijk verbindingsprobleem

  3. Hoe te SELECTEREN over twee tabellen?

  4. Ontwikkel React met full-stack (WAMP) lokaal