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

mysql join samme tabel andet resultatsæt

Det ser ud til, at det er det, du ønsker. Jeg opdaterede den første forespørgsel til at bruge korrekt ANSI JOIN syntaks og derefter for de yderligere to forespørgsler blev de forbundet via en LEFT JOINstats_host felt:

SELECT s.stats_host,
  h.host_name,
  s.stats_avgcpu,
  s.stats_avgmem,
  s.stats_avgswap,
  s.stats_avgiowait,
  s7.7dayavgcpu,
  s7.7dayavgmem,
  s7.7dayavgswap,
  s7.7dayavgiowait,
  s30.30dayavgcpu,
  s30.30dayavgmem,
  s30.30dayavgswap,
  s30.30dayavgiowait
FROM sar_stats s
INNER JOIN sar_hosts h
  on s.stats_host = h.host_id
INNER JOIN sar_appgroups a
  on h.host_appgroup = a.group_id
  and a.group_name = 'Pervasive'
INNER JOIN sar_environments e
  on h.host_environment = e.env_id
  and e.env_name = 'Staging 2'
LEFT JOIN
(
  SELECT s.stats_host,
    AVG(s.stats_avgcpu) AS '7dayavgcpu',
    AVG(s.stats_avgmem) AS '7dayavgmem',
    AVG(s.stats_avgswap) AS '7dayavgswap',
    AVG(s.stats_avgiowait) AS '7dayavgiowait'
  FROM sar_stats s
  WHERE DATE(stats_report_time) BETWEEN DATE_SUB(curdate(), INTERVAL 8 DAY) AND DATE_SUB(curdate(), INTERVAL 1 DAY)
  GROUP BY s.stats_host
) s7
  on s.stats_host = s7.stats_host
LEFT JOIN
(
  SELECT s.stats_host,
    AVG(s.stats_avgcpu) AS '30dayavgcpu',
    AVG(s.stats_avgmem) AS '30dayavgmem',
    AVG(s.stats_avgswap) AS '30dayavgswap',
    AVG(s.stats_avgiowait) AS '30dayavgiowait'
  FROM sar_stats s
  WHERE DATE(s.stats_report_time) BETWEEN DATE_SUB(curdate(), INTERVAL 31 DAY) AND DATE_SUB(curdate(), INTERVAL 1 DAY)
  GROUP BY s.stats_host
) s30
  on s.stats_host = s30.stats_host
WHERE DATE(s.stats_report_time) =  DATE_SUB(curdate(), INTERVAL 1 DAY);

se SQL Fiddle with Demo




  1. SQLskills Wait Types Library viser nu SentryOne-data

  2. Beregn 1 uge før sidste søndag og fra i dag til sidste søndag

  3. Flere indsæt sætninger i enkelt ODBC ExecuteNonQuery (C#)

  4. MySQL-kommandoer:Snydeark med almindelige MySQL-forespørgsler