Question

So, I have an array id=>time and a table.

| id | text | created_at |

How to get all rows where CREATED_AT>array['id'] and ID=id in one query?

i can do, something like this

  foreach (array as $key=>$value) {
    query("SELECT * FROM table WHERE CREATED_AT>$value and ID=$key");
  }

but i would like to put it all in one query.

Sample data:

| id | text | created_at |
--------------------------
| 1  | aaaa | 123        |
| 2  | bbbb | 124        |
| 1  | cccc | 122        |
| 3  | dddd | 125        |
| 1  | eeee | 125        |

array( '1' => 123, '2' => 125, '3' => 124);

Query should return this rows:

| 1 | aaaa | 123 |
| 3 | dddd | 125 |
| 1 | eeee | 125 |
Was it helpful?

Solution

You could do a long series of

$my_query = "SELECT * FROM table WHERE";
$counter = 0;
foreach (array as $key=>$value) {
    if ($counter > 0)
        $my_query += " OR ";
    $my_query += "(CREATED_AT>$value and ID=$key)";
    $counter++;
}

However this is ugly. I wouldn't recommend doing it. Aside from that I think there's no easy way to do this in one query. It would be easy if there was just a single batch of IDs you are querying for, but given both criteria I can't think of any other way.

I don't think it's such a bad idea to do it in a for loop... It's definitely more readable than the code I gave above.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top