简体   繁体   中英

Optimaze Mysql Query Group Concat with Left Join

here is my query

select image_tree.id, image_tree.parent_id, image_tree.url,
                           CONCAT(
                                '[',
                               GROUP_CONCAT(
                              JSON_OBJECT(
                                 'lang', image_tree_title.lang,
                                 'title', image_tree_title.title
                                   )
                          ), ']'
                       ) AS lang from `image_tree` 
left join `image_tree_title` on `image_tree_title`.`image_tree_id` = `image_tree`.`id` 
group by `image_tree`.`url`, `image_tree`.`id` 
order by url + 0 ASC

I was given advice to remove GROUP_CONCAT and sort data in PHP. Will GROUP_CONCAT have significant impact on performance, What is better approach, i think that it way better to prepare all data in MYSQL and no need for additional loops in PHP.

You really are better off just querying for the fields you need and assembling them client side. Your current GROUP_CONCAT AND JSON_OBJECT approach puts more work on the database server, locks the tables longer, and increased the amount of data that has to be packaged up and sent from the database to client code. Unless MySQL has some magic compression going on within the connection or special packing for JSON objects, it is going to be passing back numerous, redundant copies of your column name (along with formatting) for each data value you are retrieving.

I wouldn't say never use GROUP_CONCAT, it can even be used to do work that could be too expensive on particularly weak clients.... but it does come with overhead; a raw INT like 10000 can basically be sent in 4 bytes, but best case scenario a string 10000 takes 5 bytes. JSON adds even more overhead; while GROUP_CONCAT expands smaller datatypes, and adds a little more for separators, JSON does that and adds redundant field naming syntax.

Sorting in SQL is fine though, it's what it was built for (though I think that is even avoided when possible in extremely high demand systems).

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