X
X
XenK2016-07-25 06:32:17
PHP
XenK, 2016-07-25 06:32:17

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)

It is necessary to change type to perform several queries, for example (type is different, i.e. not from 0 - 1000):
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)
...

How can such a query be optimized?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
atis //, 2016-07-25
@atis2345

SELECT * FROM accounts WHERE type IN (1, 2)
UNION ALL
SELECT * FROM accounts WHERE type IN (3, 4)

And what for some times request to fulfill? After all, you can pass several types at once by calculating them somewhere beforehand!
UPD: an example in two minutes
$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);

A
Alexey, 2016-07-25
@k1lex

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()

D
Dmitry Kovalsky, 2016-07-25
@dmitryKovalskiy

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 question

Ask a Question

731 491 924 answers to any question