Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group results with conditions?

Tags:

mysql

I cannot solve this problem for many hours.
This is my table

t1:

–––––––––––––––––––––––––––––––––––
| id | text   |  lang | transl_id |
–––––––––––––––––––––––––––––––––––
| 1  | first  |  en   |  222      |
–––––––––––––––––––––––––––––––––––
| 2  | second |  de   |  222      |
–––––––––––––––––––––––––––––––––––
| 3  |   jkj  |  de   |  234      |
–––––––––––––––––––––––––––––––––––
| 4  |  89080 |  de   |  235      |
–––––––––––––––––––––––––––––––––––

Here is my query:

SELECT
    transl_id AS property,
    (SELECT text FROM t1 WHERE lang='en') AS value1,
    (SELECT text FROM t1 WHERE lang='de') AS value2,

FROM t1

It returns following table:

–––––––––––––––––––––––––––––––––––
| property  |  value1  |  value2  |
–––––––––––––––––––––––––––––––––––
|    222    |  first   |          |
–––––––––––––––––––––––––––––––––––
|    222    |          |  second  |
–––––––––––––––––––––––––––––––––––
|    234    |  jkj     |          |
–––––––––––––––––––––––––––––––––––
|    235    |  89080   |          |
–––––––––––––––––––––––––––––––––––

Each row has either value1 or value2, never both. Is there a way to group results so that rows with equal values for property field would be in one row? I mean something like this:

–––––––––––––––––––––––––––––––––––
| property  |  value1  |  value2  |
–––––––––––––––––––––––––––––––––––
|    222    |  first   |  second  |
–––––––––––––––––––––––––––––––––––
...
like image 318
Vlad T. Avatar asked Dec 22 '25 00:12

Vlad T.


1 Answers

Try this query:

SELECT
    property,
    max(value1) as Value1,
    max(value2) as Value2
FROM 
(
SELECT transl_id AS property,
    CASE when lang = 'en' then text else null end as value1,
    CASE when lang = 'de' then text else null end as value2
FROM t1
) t
GROUP BY property

See this SQLFiddle

Tried adding more values in the table and got the desired result in this SQLFiddle.

like image 122
Himanshu Jansari Avatar answered Dec 23 '25 13:12

Himanshu Jansari