简体   繁体   English

mysql列名和字段值作为行

[英]mysql column name and field value as row

I am trying to feed a data visualization program which uses sql queries. 我正在尝试提供使用sql查询的数据可视化程序。 In order to create a pie chart, it wants the input to look as follows: 为了创建饼图,它希望输入看起来如下:

+--+-----+-----+-----+
|SliceName|SliceValue
+--+-----+-----+-----+
|Slice 1  |1
+--+-----+-----+-----+
|Slice 2  |5
+--+-----+-----+-----+

Our product data is stored in a table like this: 我们的产品数据存储在这样的表中:

+--+-----+-----+-----+
|ProductID|Slice 1 | Slice 2
+--+-----+-----+-----+
|123      |1       |5
+--+-----+-----+-----+

Additional products being stored on additional rows. 其他产品将存储在其他行中。 We need to retrieve one of these rows using the ProductID, then create sql output which looks like the table in the first example. 我们需要使用ProductID检索这些行之一,然后创建类似于第一个示例中的表的sql输出。 I have read some posts about "pivoting", but I'm not sure that is exactly what we need to do here. 我已经阅读了一些有关“旋转”的文章,但是我不确定这正是我们在这里需要做的。

Can anyone offer some pointers? 谁能提供一些建议?

Is it possible to change your database schema (and do you have the appetite to do so)? 是否可以更改数据库模式(您有这样做的胃口)? Your problem could be resolved by looking at data normalisation and the relationships within the database. 通过查看数据规范化和数据库内的关系可以解决您的问题。

I would take the information relating to the slices out of the Products table and into a new table called Slices . 我会将与切片有关的信息从“ 产品”表中取出,放到名为“ 切片”的新表中。

Have a look at this SQL Fiddle example. 看一下这个SQL Fiddle示例。

You'll see that I've created a FK in the Slices table: 您会看到我已经在Slices表中创建了FK:

FOREIGN KEY (ProductID) REFERENCES Products(ProductID)
    ON DELETE CASCADE
    ON UPDATE CASCADE

So that if you delete a row from the Products table, the data in the Slices table that relates to that ProductID will also be deleted. 因此,如果您从“ 产品”表中删除一行,则“ 切片”表中与该ProductID相关的数据也将被删除。 Also if you were to update the ProductID in the Products table, then this change would be cascaded to the Slices table too. 同样,如果您要更新Products表中的ProductID ,那么此更改也将级联到Slices表中。

Now to get the data in the format that you want, you could either SELECT from Slices direct using ProductID or use a SQL statement with an INNER JOIN to SELECT based on another column in the Products table, eg 现在,要以所需的格式获取数据,您可以使用ProductID直接从Slices中进行SELECT ,或者使用基于INNER JOIN的SQL语句基于Products表中的另一列进行SELECT ,例如

SELECT SliceName, SliceValue
FROM Slices s
INNER JOIN Products p ON s.ProductID = p.ProductID
WHERE ProductName = "widget"

Storing your slices in a separate table like this be more efficient and provide flexibility; 像这样将切片存储在单独的表中会更有效并提供灵活性。 unless you always have a fixed number of slices for every product. 除非每个产品始终有固定数量的切片。

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

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