Mysql将2个查询合二为一

时间:2013-12-04 10:20:29

标签: php mysql sql join subquery

我有2个查询:第一个将检索具有最大延迟的5个用户,并且我在while循环内运行第二个查询以检索用户的用户名和名称。 这就是它的样子:

select UserID, SUM(delay) as 'TOTdelay' FROM logboek WHERE date >= x AND date <= y GROUP BY UserID ORDER BY TOTdelay DESC LIMIT 5
while ($stmt->fetch()) {
   select Username, Name FROM users WHERE ID = $UserID LIMIT 1;
   echo $Username.' on the x place with a total delay of '.$TOTdelay;
}

如何将这2个查询组合成1,这样我就不必在while循环中运行查询了?

感谢您帮助我!

2 个答案:

答案 0 :(得分:1)

您可以使用INNER JOIN

SELECT
  Username,
  Name,
  SUM(delay) AS `TOTdelay`
FROM
  logboek
INNER JOIN
  users ON UserId = users.ID
WHERE
  date BETWEEN 20130101 AND CURDATE()
GROUP BY
  UserID
ORDER BY
  TOTdelay DESC
LIMIT 5

答案 1 :(得分:0)

尝试

select logboek.UserID, SUM(logboek.delay) as 'TOTdelay', users.Username, users.Name FROM logboek
LEFT JOIN users on (users.id = logboek.UserID)
 WHERE logboek.date >= x AND logboek.date <= y GROUP BY logboek.UserID ORDER BY TOTdelay DESC LIMIT 5