Mysql:
Table_A
------------
id name
1 Name1
2 Name2
Table_B
------------
a_id type value
1 width 100
1 height 100
1 color red
2 width 50
2 height 80
It's unknown how many type values exist in Table_B.
how to get result as:
id name width height color
1 Name1 100 100 red
2 Name2 50 80 null
SELECT a.id, a.name, b_Width.value AS width, b_Height.value AS height, b_color.value AS color
FROM Table_A AS a
JOIN Table_B AS b_Width
ON b_Width.a_id = a.id AND b_Width.type = 'width'
JOIN Table_B AS b_Height
ON b_Height.a_id = a.id AND b_Height.type = 'height'
JOIN Table_B AS b_Color
ON b_Color.a_id = a.id AND b_Color.type = 'color'
But seriously consider redesigning your schema. value is holding colors and linear dimensions, it'd be better if it were designed differently.
Keep TableA the way it is but then have a table called Details that has width/height/color columns. Or have a table called Size with width/height columns and a table called Color with the color name or RGB value. Each additional table of course has an FK to TableA which may or may not be used as that table's PK.
Well, I wouldn't recommend using the EAV anti-pattern for databases as it basically holds unstructured data in a structured databases, but I have had to battle with it once before, so here is something much much faster then inner joins
select a.id, a.name, max(case when b.type='height' then b.value end) as height, max(case when b.type='width' then b.value end) as width, max(case when b.type='color' then b.value end) as color from test.tablea a , test.tableb b where a.id = b.a_id group by a.id
use select query with sub Query
like select id,Name,(select type from table_B where a_id = table_A.id and type='width') as width from table_A
same like this you can add another columns you need ok
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.