加入多个MySQL语句

时间:2013-08-25 19:06:32

标签: mysql join

我有多个要执行的查询,我想加入。

第一个查询将用户提供的路径转换为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为UNIQUE,因此不能有多行):

SELECT * FROM places WHERE id={id}

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

1 个答案:

答案 0 :(得分: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;