在MySQL中加入新列一对多
问题描述:
前几天我问了一个类似的问题,但似乎没有人能够回答它,并在网上搜索了几天,但仍然没有结果,也许我没有问提问正确的方法:One-to-many Query in 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)
);
我想是组织左侧的FIRST_NAME,只发生一次,然后每年列表中的付款金额中单独列,因为我将附加到WPF,我想要一个数据的电子表格样式表示。因此,理想的情况下应该是这样的:
name 2009 2008 2007
John 500 600 NULL
Anne NULL 500 600
Bob NULL NULL 600
我的方法是计算不同年费的次数,并用其作为一个循环计数器。比循环和收集每年的数据。以年份编号表示amount_paid的每一列。我不是不知道该怎么做,因为我最初的方法是使用UNION,但是我意识到只是将所有内容放在同一列而不是单独列。那么我应该使用什么?我只是要求一些指导。谢谢!
答
用途:
SELECT c.first_name,
MAX(CASE WHEN p.year = 2009 THEN c.amount_paid ELSE NULL END) AS 2009,
MAX(CASE WHEN p.year = 2008 THEN c.amount_paid ELSE NULL END) AS 2008,
MAX(CASE WHEN p.year = 2007 THEN c.amount_paid ELSE NULL END) AS 2007
FROM CUSTOMER c
JOIN PAYMENT p ON p.customer_id = c.customer_id
GROUP BY c.first_name
答
我没有测试,但我认为像这样的工作:
select * from ((select name, sum(amount_paid) as 2009 from customer, payment
where customer.customer_id = payment.customer_id
and payment.year = 2009) a,
(select name, sum(amount_paid) as 2008 from customer, payment
where customer.customer_id = payment.customer_id
and payment.year = 2008) b
(select name, sum(amount_paid) as 2007 from customer, payment
where customer.customer_id = payment.customer_id
and payment.year = 2007) c);
太美了!非常感谢你,我的大脑现在可以休息了。 – MCH 2010-08-11 21:30:37