在 MySQL 一对多中加入新列
前几天我问了一个类似的问题,但似乎没有人能够回答,并且在互联网上搜索了几天但仍然没有结果,也许我没有以正确的方式问问题: MySQL 中的一对多查询
所以我再次尝试,也许措辞有点不同。这本质上是我想要做的事情的简化版本:
CREATE TABLE Customer(
customer_id INT NOT NULL,
first_name varchar(20),
last_name varchar(20)
);
CREATE TABLE Payment(
customer_id INT NOT NULL,
amount_paid INT,
year YEAR,
FOREIGN KEY (customer_id) REFERENCES Customer(customer_id)
);
我想要的是组织左侧的名字,只出现一次,然后每年在单独的列中列出付款金额,因为我将附上这个到 WPF,我想要数据的电子表格样式表示。因此,理想情况下它看起来像这样:
name 2009 2008 2007
John 500 600 NULL
Anne NULL 500 600
Bob NULL NULL 600
我的方法是计算不同付款年份的数量,并将其用作循环计数器。然后循环并收集每年的数据。用年份数字表示 amount_paid 的每一列。我不仅不确定如何做到这一点,因为我最初的方法是使用 UNION,但我意识到,只需将所有内容放在同一列中,而不是单独的列中。那么我应该使用什么呢?我只是请求一些指导。谢谢你!
I asked a similar question the other day but it seems no one was able to answer it, and searched the internet for a few days but still fruitless, perhaps I am not asking the question the right way: One-to-many Query in MySQL
So I while try again and maybe word it a bit differently. This is essentially a simplified version of what I am trying to do:
CREATE TABLE Customer(
customer_id INT NOT NULL,
first_name varchar(20),
last_name varchar(20)
);
CREATE TABLE Payment(
customer_id INT NOT NULL,
amount_paid INT,
year YEAR,
FOREIGN KEY (customer_id) REFERENCES Customer(customer_id)
);
What I want is to organize the first_name on the left, only occurring once, and then for each year list the payment amount in separate columns because I am going to be attaching this to WPF and I want a spreadsheet style representation of the data. So, ideally it would look like this:
name 2009 2008 2007
John 500 600 NULL
Anne NULL 500 600
Bob NULL NULL 600
My approach is to count the number of distinct years of payments, and use that as a loop counter. than loop through and collect the data for each year. Represent each column of amount_paid by the year number. I am not just not sure how to do that, because my initial approach was to use UNION, but than I realized that just puts everything in the same column as opposed to separate ones. So what should I be using? I am only asking for some guidance. Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用:
Use:
不幸的是,mysql 没有
pivot
功能,因此唯一可能的方法是使用任何编程语言格式化结果集。mysql unfortunately has no
pivot
feature, so the only possible way is to format the result set with any programming language.我没有测试过,但我认为这样的方法是有效的:
I hadn't test it but I think something like this works: