简体   繁体   English

MySQL将2个查询合二为一

[英]Mysql joining 2 query's in one

I have 2 query's: the first one will retrieve the 5 users with the most delay and i am running inside the while loop a second query for retrieving the users username and name. 我有2个查询:第一个查询将检索延迟最大的5个用户,而我在while循环中运行第二个查询以检索用户的用户名和名称。 This is how it looks like: 它是这样的:

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;
}

How can i combine this 2 query's in to 1 so i don't have to run a query inside my while loop? 如何将这2个查询合并为1,这样我就不必在while循环内运行查询?

Thanks for helping me out! 谢谢你的协助!

You can use INNER JOIN : 您可以使用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

Try 尝试

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

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

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