Answer the question
In order to leave comments, you need to log in
Substitute values one by one in SQL query?
There is a request like this:
SELECT sum(money) FROM `accounts` WHERE date >= (CURDATE()-1) AND date < CURDATE() AND type IN (101,225)
SELECT sum(money) FROM `accounts` WHERE date >= (CURDATE()-1) AND date < CURDATE() AND type IN (353,448).
SELECT sum(money) FROM `accounts` WHERE date >= (CURDATE()-1) AND date < CURDATE() AND type IN (458,248)
...
Answer the question
In order to leave comments, you need to log in
SELECT * FROM accounts WHERE type IN (1, 2)
UNION ALL
SELECT * FROM accounts WHERE type IN (3, 4)
$sql = [];
$params = [];
$PDO; // Создаете PDO объект
for($i = 0, $max = 10; $i < $max; $i++) {
$sql[] = "SELECT * FROM accounts WHERE type IN (?, ?)\r\n";
$params[] = 0; // число 1
$params[] = 1; // число 2
}
$query = implode("UNION ALL\r\n", $sql);
$sth = $PDO->prepare($query);
foreach($params as $key => $value) {
$sth->bindValue($key, $value);
}
$sth->execute();
$sth->fetchAll(PDO::FETCH_ASSOC);
Create a temporary table where there will be two fields: 1e - the first value of type, 2e - the second value.
Let's say it will be a tmp_type table with type1 and type2 fields.
Then we write the following query:
SELECT tmp_type.type1,tmp_type.type2,sum(money) FROM `accounts`
inner join tmp_type ON tmp_type.type1 =accounts.type or tmp_type.type2 =accounts.type
group by tmp_type.type1,tmp_type.type2
WHERE date >= (CURDATE()-1) AND date < CURDATE()
I may not understand something. And what forbids you to make a selection for all the necessary types, and then sort out the data at the application level? What for here union and plural standard requests?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question