jeudi 31 mars 2016

how to generate a number of rows based on field value in SQLite

I'm going over lots of old code and see how much I can optimize them using new stuff I learned. One feels like there is a cleaner way to do it, but I can't figure out what!

I do have the following tables that can be summarize like:

Table summary
-------------------------    
category  | group | rows | priority
------------------------
1         | 1     | 3    | 1
2         | 1     | 3    | 2
3         | 2     | 2    | 1
4         | 2     | 2    | 2
5         | 2     | 2    | 3

Table article
-------------------------------    
article   | category | somedata
-------------------------------
1         | 1        | blabla
2         | 1        | blabla
3         | 2        | blabla
4         | 2        | blabla
5         | 1        | blabla
6         | 1        | blabla
7         | 1        | blabla
8         | 2        | blabla
9         | 3        | blabla
10        | 3        | blabla
11        | 3        | blabla
12        | 4        | blabla
13        | 4        | blabla
14        | 4        | blabla
15        | 4        | blabla
16        | 5        | blabla
17        | 5        | blabla
18        | 5        | blabla
19        | 5        | blabla

My current approach is to do it in two requests like (super simplified for reading purpose)

$category = $db->query("SELECT category, group, rows FROM summary ORDER BY 
group, priority");
$feed = $db->prepare("SELECT article, someData FROM article 
WHERE category = :category LIMIT 0,:rows");

foreach($category as $cat){
    $feed->bindParam(":category",$cat['category'], SQLITE3_INT);
    $feed->bindParam(":rows",$cat['rows'], SQLITE3_INT);
    $feed->execute();
    //some code,exception and data processing handling 
}

Is it possible to do it in only one request straight in SQLite3 and get something like the following response ?

-------------------------    
category  | group | article | someData
------------------------
1         | 1     | 1       | blabla 
1         | 1     | 2       | blabla 
1         | 1     | 5       | blabla 
2         | 1     | 3       | blabla 
2         | 1     | 4       | blabla 
2         | 1     | 8       | blabla 
3         | 2     | 9       | blabla 
3         | 2     | 10      | blabla 
4         | 2     | 12      | blabla 
4         | 2     | 13      | blabla 
5         | 2     | 16      | blabla 
5         | 2     | 17      | blabla 

Aucun commentaire:

Enregistrer un commentaire