Last active
August 16, 2023 05:08
-
-
Save zhiephie/38ed3dafa3b8076385c57100372e4892 to your computer and use it in GitHub Desktop.
Performance Increase using Dynamic SQL Generation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Expand your date range to an array | |
const dates = [ | |
'2023-08-01', | |
'2023-08-02', | |
'2023-08-03', | |
'2023-08-04' | |
] | |
// Define the static part of your query | |
let query = `SELECT hotelRoomId, MIN(price) | |
FROM room_pricing | |
WHERE (` | |
//Iterate and build your query dynamically | |
let i = 0 | |
for (const date of dates){ | |
//iteratively add your equality clauses | |
query += `date = ${date}` | |
// Add OR condition for all but last case | |
if(i < dates.length - 1){ | |
query += ` OR ` | |
} | |
i++ | |
} | |
query += `) | |
GROUP BY hotelRoomId` | |
console.log(query) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$start_date = '2012-01-01'; | |
$end_date = '2012-12-31'; | |
$start = new DateTime($start_date); | |
$end = new DateTime($end_date); | |
$end->modify('+1 day'); | |
$interval = new DateInterval('P1D'); // 1 day interval | |
$period = new DatePeriod($start, $interval, $end); | |
$dates = []; | |
foreach ($period as $day) { | |
$dates[] = $day->format('Y-m-d'); | |
} | |
// Define the static part of your query | |
$query = "SELECT hotelRoomId, MIN(price) | |
FROM room_pricing | |
WHERE ("; | |
//Iterate and build your query dynamically | |
$i = 0; | |
foreach ($dates as $date) { | |
//iteratively add your equality clauses | |
$query .= "date = {$date}"; | |
// Add OR condition for all but last case | |
if($i < count($dates) - 1) { | |
$query .= " OR "; | |
} | |
++$i; | |
} | |
$query .= ") | |
GROUP BY hotelRoomId"; | |
echo $query; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment