[英]Mysql double query request
I have a tables: 我有一张桌子:
table_1
id time
1 2012-03-05 12:50:00
2 2012-03-05 12:51:00
3 2012-03-05 12:52:00
4 2012-03-05 12:53:00
table_2
userid level
100 1
256 2
112 3
400 2
15 1
First request: 第一个要求:
$sql = 'SELECT `id`, `time` FROM table_1 WHERE `time` > NOW() ORDER BY `id` DESC LIMIT 1';
Second request: 第二个请求:
$sql = 'SELECT COUNT(*) FROM table_2 WHERE `userid` = 100 LIMIT 1';
How to combine these two requests into one request? 如何将这两个请求合并为一个请求?
For example this table: 例如此表:
id time count
1 2012-03-05 12:53:00 1
Or 要么
id time count
1 2012-03-05 12:53:00 0
If we have no any records in table_2 Thanks! 如果table_2中没有任何记录,谢谢!
Combining two very simple, unrelated queries into a single more complex one is not the best way to gain performance. 将两个非常简单,不相关的查询合并为一个更复杂的查询并不是获得性能的最佳方法。 You may get a slight boost from one less round trip, but the queries will quickly become unmaintainable.
往返次数减少可能会稍微增加一点,但是查询很快将变得难以维护。
Instead, to avoid an extra round trip time, use something like mysqli::multi_query to send them both at the same time to the database. 相反,为了避免额外的往返时间,请使用mysqli :: multi_query之类的东西将它们同时发送到数据库。 That means you can keep the queries simple, and still get only one round trip to the database.
这意味着您可以使查询保持简单,并且仍然只能往返数据库一次。
Since they are in no way related, simple but brute force, I would do this. 由于它们毫无关系,既简单又蛮力,所以我会这样做。 Not practical, but would do it.
不切实际,但是会做到的。
SELECT
`id`,
`time`,
( select COUNT(*)
FROM table_2
WHERE `userid` = 100 ) as UserCount
FROM
table_1
WHERE
`time` > NOW()
ORDER BY
`id` DESC
LIMIT 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.