0

我有多个我想一起执行的查询。

第一个查询将用户提供的路径转换为 ​​id。路径可以有多个与之关联的 id,因此我想确保获得最近创建的路径 id:

SELECT id FROM paths WHERE path=$path ORDER BY created DESC LIMIT 1

一旦我知道了身份证号码,我就可以执行其余的查询。

我有最近创建的路径 ID,但我还需要验证我有最近创建的该 ID 路径(有时它们不一样):

SELECT path FROM paths WHERE id={id} ORDER BY created DESC LIMIT 1

我想包括 id 的评级和票数,尽管有时没有:

SELECT AVG(vote) AS rating, COUNT(*) AS count FROM votes WHERE id={id} GROUP BY id

最后,我想包括第三个表中关于 id 的所有内容(该表上的 id 是唯一的,因此不能有多行):

SELECT * FROM places WHERE id={id}

我怎样才能最好地将这些陈述结合在一起?

4

1 回答 1

0

您可以将它们连接到一个查询中,如下所示:

select pl.*, avg(vote) as rating
from (SELECT path, id
      FROM paths
      WHERE path = {path}
      ORDER BY created DESC
      LIMIT 1
     ) p left outer join
     votes v
     on v.id = p.id left outer join
     places pl
     on pl.id = p.id
group by p.id;

编辑:

前两个条件似乎是多余的。但是,如果您需要它们:

select pl.*, avg(vote) as rating
from (SELECT path, id
      FROM paths
      WHERE id = (select id from paths where path = {path} order by created desc limit 1)
      ORDER BY created DESC
      LIMIT 1
     ) p left outer join
     votes v
     on v.id = p.id left outer join
     places pl
     on pl.id = p.id
group by p.id;
于 2013-08-25T19:21:06.483 回答