如何使用现有字段(表的另一个字段)中的某些偏移量(表的字段)在视图中创建新字段?

时间:2014-06-16 18:24:01

标签: mysql sql date sql-view

我有表Contracts

CREATE TABLE `Contracts` (
    `id` INT(11) NOT NULL AUTO_INCREMENT,
    `supplier_id` INT(11) NOT NULL,
    `shop_id` INT(11) NOT NULL,
    `conclusionDate` DATE NOT NULL,
    `period` INT(11) NOT NULL,
    PRIMARY KEY (`id`),
    CONSTRAINT `FK_Contracts_Shop` FOREIGN KEY (`shop_id`) REFERENCES `shop` (`id`),
    CONSTRAINT `FK_Contracts_Suppliers` FOREIGN KEY (`supplier_id`) REFERENCES `suppliers` (`id`)
)

我想创建这样的东西:

SELECT 
    c.id, 
    s.name as supplierName,
    c.conclusionDate, 
    c.conclusionDate+year(c.period) as cancelDate, 
    c.period
FROM
    Contracts as c
INNER JOIN
    Suppliers as s
ON 
    s.id = c.supplier_id 

这是我目前的观点代码。因此,我想要从结束日期(period字段 - 日期类型)获取取消日期为日期的行,其中包含年份(conclusionDate字段 - 整数类型)的偏移量。

昨天,我看到了这样的例子,但我现在找不到了:(请帮帮我。

预期结果:

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+ id + supplierName + conclusionDate + cancelDate + period +
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+ 1  + bob1         + 2014-05-05     + 2015-05-05 + 1      +
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+ 2  + bob2         + 2014-01-01     + 2018-05-05 + 4      +
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+ 3  + bob3         + 2012-08-03     + 2017-08-03 + 5      +
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

2 个答案:

答案 0 :(得分:1)

尝试使用interval添加您的句点列与您的结论日期

c.conclusionDate + interval c.period year as cancelDate

Demo

答案 1 :(得分:0)

这应该有用。

ADDDATE(c.conclusionDate, INTERVAL c.period YEAR) as cancelDate,