且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在多个SQL查询之间保留变量(不嵌套查询)?

更新时间:2023-01-24 15:47:17

sql1 = SELECT * FROM(select * from my_table WHERE id<

id ORDER BY id DESC LIMIT 1)AS x ORDER BY id LIMIT 1;


result1 = mysqli_query(


I'd like to know what is the best approach to retain variables between multiple queries and echo them out in the last query. My current logic is to nest the queries, like the example below.

I heard that nesting slows down a program, and that it's unnecessarily verbose, and bad practise in general. I heard about "join" and "left join" but I've no idea how to apply it in an example or how to convert something like the following code into a "join" statement.
Can anybody tell me how to re-construct my code using best practises?

What I have tried:

/*First SQL query:*/
	$sql1 = "SELECT * FROM (select * from my_table WHERE id < $id ORDER BY id DESC LIMIT 1) AS x ORDER BY id LIMIT 1";
	$result1 = mysqli_query($conn, $sql1);
	$resultCheck1 = mysqli_num_rows($result1);
	if ($resultCheck1 > 0) {
		while ($row1 = mysqli_fetch_assoc($result1)) {
			$sum1 = $row1['sum'];
			/*Second SQL query:*/
			$sql2 = "SELECT * FROM (select * from my_table WHERE id = $id ORDER BY id DESC LIMIT 1) AS x ORDER BY id LIMIT 1";
			$result2 = mysqli_query($conn, $sql2);
			$resultCheck2 = mysqli_num_rows($result2);
			if ($resultCheck2 > 0) {
				while ($row2 = mysqli_fetch_assoc($result2)) {
					$sum2 = $row2['sum'];
					/*Third SQL query:*/
					$sql3 = "SELECT * FROM new_table"; /*Different table*/
					$result3 = mysqli_query($conn, $sql3);
					$resultCheck3 = mysqli_num_rows($result3);
					if ($resultCheck3 > 0) {
						while ($row3 = mysqli_fetch_assoc($result3)) {
							$sum3 = $row3['sum'];
							echo $sum1 + $sum2 + $sum3;
						}
					}
				}
			}
		}
	}

sql1 = "SELECT * FROM (select * from my_table WHERE id <


id ORDER BY id DESC LIMIT 1) AS x ORDER BY id LIMIT 1";


result1 = mysqli_query(