2014-07-19 130 views
0

我需要重新命名我的一些MySQL表,從而弄亂我的程序。至少這就是我的想法......我得到一個前所未有的錯誤。'where子句'中未知的列'discussion.rubric_id'

兩個表格很重要:一個稱爲rubrics,它有一列來計算與rubric相關的discussions。因此,無論何時插入新的discussion,都會觸發procedure,使計數器增加。

這是兩個表(簡稱):

這是我專欄

CREATE TABLE IF NOT EXISTS `rubric` (
    `id` INT NOT NULL AUTO_INCREMENT , 
    `topic_id` INT NOT NULL , 
    `name` VARCHAR(50) NULL , 
    `description` TEXT NULL , 
    `total_discussions` INT NULL DEFAULT 0 , // this is the COUNTER 
    `latest_activity_id` INT NULL , 
    PRIMARY KEY (`id`, `topic_id`) , 
... // just some index and constraint.. 
ENGINE = InnoDB; 

這是我討論

CREATE TABLE IF NOT EXISTS `discussion` (
    `id` INT NOT NULL AUTO_INCREMENT , 
    `rubric_id` INT NOT NULL ,  // as you can see it has a rubric_id column 
    `topic_id` INT NOT NULL , 
    `latest_activity_id` INT NULL DEFAULT 0 , 
    `name` VARCHAR(50) NULL , 
    `description` TEXT NULL , 
    `total_posts` INT NULL DEFAULT 0 , 
    `total_views` INT NULL DEFAULT 0 , 
    PRIMARY KEY (`id`, `rubric_id`, `topic_id`) , 
    ... // just some index and constraint.. 
ENGINE = InnoDB; 

這裏是程序應該增加計數器評鑑表:

DELIMITER $$ 

CREATE TRIGGER count_discussions AFTER INSERT ON discussion 
FOR EACH ROW 
BEGIN 
    UPDATE rubric SET total_discussions = total_discussions + 1 WHERE rubric.id = discussion.rubric_id; 
END $$ 

插入新行的時候,我得到的錯誤是:

Error code 1054, SQL state 42S22: Unknown column 'discussion.rubric_id' in 'where clause' 

所以我猜測它是關於的WHERE子句程序因爲我沒有其他WHERE子句提到rubric_id co lumn。但正如您在討論表中看到的那樣,該列存在。那麼這是一種我不尊重的錯字或某種語法嗎?

回答

1

試一下:

DELIMITER $$ 

    CREATE TRIGGER count_discussions AFTER INSERT ON discussion 
    FOR EACH ROW 
    BEGIN 
    UPDATE rubric 
    INNER JOIN discussion ON rubric.id = discussion.rubric_id 
    SET total_discussions = total_discussions + 1 ; 
    END $$ 

你需要加入的圓桌討論。

+0

非常感謝那個快速和工作的答案。不知道我可以加入觸發器!它現在正在工作,但我仍然想知道爲什麼它在重命名錶之前工作...謝謝! – GameDroids

+0

歡迎您:)! –