2016-11-07 110 views
0

從來就搜索了很多,但我不能弄清楚如何做到這一點,如果it's可能......使用變量,而不是字段名在MySQL中選擇查詢

我有這個表:

CREATE TABLE bilanci (
    id    int AUTO_INCREMENT NOT NULL, 
    medicoid  int NOT NULL, 
    `1`    int NOT NULL DEFAULT 0, 
    `2`    int NOT NULL DEFAULT 0, 
    `3`    int NOT NULL DEFAULT 0, 
    `4`    int NOT NULL DEFAULT 0, 
    `5`    int NOT NULL DEFAULT 0, 
    `6`    int NOT NULL DEFAULT 0, 
    `7`    int NOT NULL DEFAULT 0, 
    `8`    int NOT NULL DEFAULT 0, 
    `9`    int NOT NULL DEFAULT 0, 
    `10`   int NOT NULL DEFAULT 0, 
    `11`   int NOT NULL DEFAULT 0, 
    `12`   int NOT NULL DEFAULT 0, 
    conguagliodic decimal(10,2), 
    totbilancianno int DEFAULT 0, 
    totpagato  decimal(12,2), 
    totdapagare  decimal(12,2), 
    conguaglio  decimal(10,2), 
    rifanno   int NOT NULL, 
    pvimun   decimal(10,4) NOT NULL DEFAULT 9.4432, 
    PRIMARY KEY (id) 
) ENGINE = InnoDB; 

以數字命名的的Fileds對應個月,我需要有一個選擇,如:

select medicoid, (month(curdate()) -2), totdapagare from bilanci 

(month(curdate()) -2)符合我需要選擇的領域。

這可能嗎?

+0

它可能以某種方式成爲可能,但它不會太簡單......你不能否認你的數據庫結構嗎?不要將不同的列存儲幾個月,將月份值存儲在不同的表中 – fthiella

回答

0

我建議你一定要規範你的數據庫結構,你可以有一個表是這樣的:

CREATE TABLE bilanci (
    id    int AUTO_INCREMENT NOT NULL, 
    medicoid  int NOT NULL, 
    conguagliodic decimal(10,2), 
    totbilancianno int DEFAULT 0, 
    totpagato  decimal(12,2), 
    totdapagare  decimal(12,2), 
    conguaglio  decimal(10,2), 
    pvimun   decimal(10,4) NOT NULL DEFAULT 9.4432, 
    PRIMARY KEY (id) 
) ENGINE = InnoDB; 

和第二臺bilanci_month:

create table bilanci_month (
    id int auto_increment, 
    bilanci_id int, 
    rifanno int NOT NULL, 
    month int NOT NULL, 
    value int) 

(bilanci_id可以被定義爲一個外國bilanci_month的關鍵字),那麼您的選擇查詢將如下所示:

select 
    b.medicoid, 
    coalesce(bm.value, 0), 
    b.totdapagare from bilanci 
from 
    bilanci b left join bilanci_month bm 
    on b.id = bm.bilanci_id and bm.month = month(curdate())-2 

還要小心month(curdate())-2,如果一月份是一月份或二月份會發生什麼?你必須實現一些邏輯來獲得例如前一年的十一月或十二月(並將此邏輯添加到你的連接中)。

+0

感謝您的解決方案和建議!我試過這似乎工作正常:選擇如果((選擇月份(curdate()) - 2)= 0,12,如果((選擇月份(curdate)-2)= -1,11,(選擇月份(選擇年份(curdate())))))作爲月份並且 選擇是否((選擇月份(curdate()) - 2)<= 0,(選擇年份(curdate())-1),(選擇年份(curdate())) )爲一年 –

相關問題