S
S
Sergey2018-03-21 11:26:25
MySQL
Sergey, 2018-03-21 11:26:25

Combining Select queries into one?

There is a table:

id | user | summ | time
33 | u123 | 350 | 1000
.....
22 | u123 | 200 | 850
......
11 | u123 | 50 | 650
......

There is a working code:
$res = mysql_query("SELECT * FROM tb_history WHERE status='0'");			
while($main=mysql_fetch_array($res)){
   $id_user = $main["id_user"];    // u123
   $times = $main["time"];    // 1200
   .....

   $res2=mysql_query("SELECT * FROM tb WHERE user='$id_user' AND time<'$times' ORDER BY id DESC"); 
   while($row_tb=mysql_fetch_array($res2)){
      $us_id=$row_tb["id"];    // 33
      $_time=$row_tb["time"];    // 1000
          
      $res3=mysql_query("SELECT * FROM tb WHERE user='$id_user' AND time<'$_time' ORDER BY id DESC LIMIT 1"); 
      $row_tb=mysql_fetch_array($res3);
      $us_id=$row_tb1["id"];    // 22
      $i_time = $row_tb1["time"];    // 850
  
     $i_time3 = $_time - $i_time;    // 1000 - 850
     .....
   }
}

How to combine everything in one request, or at least res2 and res3?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Timofeev, 2018-03-21
@Set89

union or join depending on the situation, as I understand it, $res2 and $res3 are easily combined via UNION, and res1 to them via JOIN
https://www.w3schools.com/sql/sql_union.asp
https://www.w3schools .com/sql/sql_join.asp

B
Boris Korobkov, 2018-03-21
@BorisKorobkov

RTFM https://dev.mysql.com/doc/refman/5.7/en/join.html

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question