简体   繁体   中英

Is it possible to concat full record(the whole row) into one column in MySQL? and how?

I have 2 tables in my database, one is for sublets and one is for users .
The relation is that each user can have multiple sublets.
The foreign key in the sublets table is the user_id.

TABLE users {
   id,
   name
},

TABLE sublets {
   sublet_id,
   city_id,
   user_id,
   rooms,
   floor,
   price
}

Now let's say that user with id 46 has 3 sublets.

If I JOIN the sublets table:

SELECT * FROM users JOIN sublets ON users.id = sublets.user_id WHERE users.id = 46

I get 3 rows, each for each sublet.

id | name  | sublet_id | city_id | user_id | rooms | floor | price
=================================================================
46 | "Joe" |  1        | 20      | 46      | 2     | 2     | 30
46 | "Joe" |  2        | 13      | 46      | 3     | 5     | 20
46 | "Joe" |  3        | 2       | 46      | 1     | 1     | 10

is to have with all the sublets under one column called user_sublets. 是在名为user_sublets的一列下放置并将所有子子集包含在内。

For example:

id | name  | sublets
====================
46 | "Joe" | ["sublet_id":1,"city_id":20, "user_id":46,...],["sublet_id":2,...]...

So now I have all of the sublets inside this one column, you can see that I might want to use it as JSON

user: {
   "id": 46,
   "name": "Joe",
   "sublets": [
     {
        "sublet_id":1,
        "city_id":20,
        ...
     },
     {
        "sublet_id":2,
        "city_id":13,
        ...
     },
     {
        "sublet_id":3,
        "city_id":2,
        ...
     }
   ]
}

So eventually the main reason I want to achieve this result is to use it as JSON in my app with 1 query instead of the need to query the DB twice and add the sublets with a programming language(ie PHP).

To my knowledge GROUP_CONCAT can concat only one column so I can't concat all the columns, and combining it with concat is just too messy to me because if I am adding a new column to the sublets table I will have to edit my query in many different places.

What's the best solution? will it be slower to make 2 queries and concat the sublets to the user with a programming language?

Thank you in advance!

I hope I provided enough information and that I described my need clearly.

I don't know if it's a efficient solution or not, but you might use the combination of GROUP_CONCAT and CONCAT .

Like this,

SELECT 
user_id,name,
GROUP_CONCAT(CONCAT('[',
CONCAT("{'sublet_id':",sublet_id,",city_id:'",city_id,"'}"),']'))
FROM users 
JOIN sublets 
ON users.id = sublets.user_id 
WHERE users.id = 46

You can add more columns in second CONCAT() .

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