简体   繁体   English

MySQL:平均并加入两个查询

[英]MySQL: Average and join two queries

I have two queries: 我有两个查询:

SELECT
  s.id AS id,
  g.id AS group_id,
  g.nazwa AS group_name,
  s.nazwa AS station_name,
  s.szerokosc AS szerokosc,
  s.dlugosc AS dlugosc,
  s.95 as p95,
  s.98 as p98,
  s.Diesel as diesel,
  s.DieselTIR as dieseltir,
  s.Super98 as s98,
  s.SuperDiesel as sdiesel,
  s.LPG as lpg,
  s.ulica as ulica,
  s.kodPocztowy as kod_pocztowy,
  s.miasto as miasto,
  w.id as wojewodztwo_id,
  w.nazwa as wojewodzto_nazwa,
  k.id as kraj_id,
  k.kod as kraj_kod,
  k.nazwa as kraj_nazwa,
  s.data as date_mod,
  s.active as active
FROM stacje_main s
JOIN stacje_grups g ON (s.grupa=g.id)
JOIN wojewodztwa w ON (s.wojewodztwo=w.id)
JOIN kraje k ON  (w.kraj=k.id)
WHERE s.data > 0;

and

SELECT
  AVG(rr.vote) as average,
  COUNT(rr.station_id) counter
FROM stacje_ratings rr
GROUP BY rr.station_id;

In the second query not all id (station_id) are present, and sometimes are doubled. 在第二个查询中,并非所有id(station_id)都存在,有时会翻倍。 Join station_id with id, and give average value of rate for each id. 将station_id与id结合在一起,并为每个id给出rate的平均值。

The problem that when no rate, the value in question in average and counter have to be 0. 没有费率时,所讨论的平均值和计数器的值必须为0的问题。

When I combined these queries i see only this ID, that has present station_id. 当我组合这些查询时,我只能看到具有当前station_id的该ID。 But I want to see all. 但是我想看全部。

You need to use a LEFT JOIN (see MySQL JOIN syntax ). 您需要使用LEFT JOIN (请参阅MySQL JOIN语法 )。

This will return NULL for rows that have no matching row in the joined table, so I use COALESCE to replace them by 0 . 对于联接表中没有匹配行的行,这将返回NULL ,因此我使用COALESCE将它们替换为0

SELECT
  s.id AS id,
  g.id AS group_id,
  -- [...]
  COALESCE( x.average, 0 ) AS average
  COALESCE( x.counter, 0 ) AS counter
FROM stacje_main s
JOIN stacje_grups g ON (s.grupa=g.id)
JOIN wojewodztwa w ON (s.wojewodztwo=w.id)
JOIN kraje k ON  (w.kraj=k.id)
LEFT JOIN (
  SELECT
    rr.station_id
    AVG(rr.vote) as avarge,
    COUNT(rr.station_id) counter
  FROM stacje_ratings rr
  GROUP BY rr.station_id
) x ON ( x.station_id = s.id )
WHERE s.data > 0;

Dear bro, please use left / right join according to your need, you have used inner join so so it will search for same records present in both tables. 亲爱的兄弟,请根据您的需要使用左/右联接,您已经使用了内部联接,因此它将搜索两个表中存在的相同记录。

select * frm tbl right join tbl1 on tbl1.id = tbl.id 选择* frm tbl在tbl1.id = tbl.id上加入tbl1

if suppose your right table then if no matching record isn't present in tbl1 then also all those records are populated 如果假设您的表正确,那么如果tbl1中没有匹配的记录,那么所有这些记录也将被填充

same case in left join but reverse the table name only... 左联接的情况相同,但仅反转表名称...

:) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM