简体   繁体   中英

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!

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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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