简体   繁体   中英

Joins - Merge result into single, multidimensional array

I'm performing a simple query that joins two tables together. What I get is something like this.

array(
    [0] => array(
        'id' => 52
        'name' => 'charles',
        'sale_id' => 921,
        'sale_time' => 1306393996,
        'sale_price' => 54.21
    ),
    [1] => array(
        'id' => 52
        'name' => 'charles',
        'sale_id' => 922,
        'sale_time' => 1306395000,
        'sale_price' => 32.41
    ),
    ...
);

...which is the expected result. However, I'd like the query to return something like this:

array(
    [0] => array(
        'id' => 52,
        'name' => 'charles',
        'sales' => array(
            [0] => array(
                'sale_id' => 921,
                'sale_time' => 1306393996,
                'sale_price' => 54.21
            ),
            [1] => array(
                'sale_id' => 922,
                'sale_time' => 1306395000,
                'sale_price' => 32.41
            ),
            ...
        )
    )
)

Now I realize I could simply perform two queries, one for the user info, and another for sales, and merge those arrays together using whatever language I'm using (PHP in this case). But I have many arrays of properties and querying and merging for those seems awfully inelegant to me (although it does work). It seems to me there'd be a way to work with a single, unified object without duplicating data.

Just wondering if there was a no-brainer query, or if that's simply not easy through MySQL alone.

I would say this is not possible with MySQL alone - you have to do some tricks at application level. That is, because even if you send a single query that will bring you all the data from MySQL to your application (PHP), they will come as a denormalized array of data - your first case.

If you want to get the data as in your second case, I'd recommend using some ORM - in Ruby there is ActiveRecord, in Perl there are Class::DBi, DBIx::Class and many more - I can not name one for PHP that is able to do this, but I am sure there are plenty.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM