简体   繁体   English

SQL查询以形成数据

[英]A sql query to form data

Mysql: 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. 未知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. 保持TableA不变,但是有一个名为Details的表,该表具有width / height / color列。 Or have a table called Size with width/height columns and a table called Color with the color name or RGB value. 或者有一个名为Size的表,该表具有宽度/高度列,而又有一个名为Color的表,具有颜色名称或RGB值。 Each additional table of course has an FK to TableA which may or may not be used as that table's PK. 当然,每个其他表都具有TableA的FK,可以或可以不用作该表的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 好吧,我不建议对数据库使用EAV反模式,因为它基本上将非结构化数据保存在结构化数据库中,但是我之前不得不与之抗衡,所以这比内部联接要快得多

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 选择a.id,a.name,max(当b.type ='height'然后b.value结束时的情况)作为高度,max(当b.type ='width'然后b.value结束时的情况)作为宽度,最大(如果b.type ='color'然后b.value结束的情况)为test.tablea a,test.tableb b中的颜色,其中a.id = b.a_id由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 像select id,Name(从table_B选择类型,其中a_id = table_A.id并选择type ='width')作为table_A的宽度

same like this you can add another columns you need ok 像这样,您可以添加其他需要的列

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM