How to join multiple row into one row without group concat ?
Consider i have table like below:
Table user:
uid | name
-----------
1 | A
2 | B
table meta:
uid | metaid | metaval
------------------------
1 | 1 | Jsep St.
1 | 2 | St. Oak No. 15
2 | 1 | Dt. San Joseph
2 | 2 | St. Oak No. 17
2 | 3 | OA.
table metaproperty:
metaid | metakey
-----------------
1 | school
2 | address
3 | dept
4 | acc
I want to pick a user with their school and address so the query is
SELECT
uid, name, metaval
FROM user
INNER JOIN meta ON meta.uid = user.uid
WHERE meta.metaid = 1 OR meta.metaid = 2
it will output
| UID | Name | MetaVal |
--------------------------------
| 1 | A | Jsep St. |
| 1 | A | St. Oak No. 15 |
The result I want is like this
uid | name | school | address
-------------------------------------
1 | A | Jsep St.| St. Oak No. 15
With group concat, metaproperty with value “school” and “address” is not in different column but one column
I try to join twice and it work but i think it’s not elegant
SELECT
uid, name, T1.metaval as school, T2.metaval as address
FROM user
INNER JOIN meta T1 ON T1.uid = user.uid AND T1.metaid = 1
INNER JOIN meta T2 ON T2.uid = user.uid AND T2.metaid = 2
Any better solution ?
Short answer
No.
Medium length answer
There are a few problems with your query.
usertable.LEFT JOINif some data might be missing.Try this:
Long answer
Yes, that query is ugly, but the problem is not the query but the database design. The design you are using is called entity-attribute-value (EAV). Avoid using the EAV design if at all possible! Whenever you use EAV, all your queries turn into multiple join monsters. It’s much easier if you can store each value in a separate column in the same row.
Of course, there are some situations where you must use EAV. Then you just have to accept that your queries will be long, hard-to-read, inelegant and slow. That’s the tradeoff you make for having a flexible schema.