仅在表中创建新行

时间:2014-03-05 22:46:05

标签: mysql

我正在尝试移动数据并使用触发器将其转换为另一个表。 我有表设置和这个开发代码:

DELIMITER//

CREATE TRIGGER move_data AFTER 
INSERT ON schema.old_table 
FOR EACH ROW
BEGIN


DECLARE num_id_before, num_id_after INT;
SET num_id_before = (select count(id) FROM schema.old_table);
SET num_id_after = (num_id_before - 7);

INSERT INTO schema.new_table (name, street_address, 
            street_address_line_2, city, state, zip, country, fr_dob)

SELECT  MAX(CASE WHEN element_label = 0 THEN element_value end) AS name, 
    MAX(CASE WHEN element_label = 1 THEN element_value end) AS street_address, 
    MAX(CASE WHEN element_label = 2 THEN element_value end) AS street_address_line_2,
    MAX(CASE WHEN element_label = 3 THEN element_value end) AS city, 
    MAX(CASE WHEN element_label = 4 THEN element_value end) AS state,
    MAX(CASE WHEN element_label = 5 THEN element_value end) AS zip,
    MAX(CASE WHEN element_label = 6 THEN element_value end) AS country,
    MAX(CASE WHEN element_label = 7 THEN element_value end) AS dob

FROM schema.old_table 
LIMIT num_id_after, num_id_before 
GROUP BY group_id

END //
DELIMITER;

目前无需使用:

DECLARE num_id_before, num_id_after INT;
SET num_id_before = (select count(id) FROM schema.old_table);
SET num_id_after = (num_id_before - 7);

LIMIT num_id_after, num_id_before

添加了这些代码后,我收到了这个错误:

 Error Code: 1064. You have an error in your SQL syntax; check the manual that  corresponds to your MySQL server version for the right syntax to use near 'num_id_after, num_id_before GROUP BY group_id END' at line 22

〜编辑:我知道这是基本上“通用错误”的一般错误,但它可能有助于诊断,我对mysql相当新鲜

唯一的问题是它每次运行时都会复制所有以前的数据,而不仅仅是新添加的行。目前,旧表设置数据,因为每个值都是组中的单独行。我需要它在一个新表中,每个组都在一行中。

任何人都可以帮忙吗?随意询问更多信息

1 个答案:

答案 0 :(得分:1)

正如@M Khalid Junaid所说,改变你的条款的顺序:

FROM schema.old_table 
GROUP BY group_id
LIMIT num_id_after, num_id_before;

END //

GROUP BY子句总是在LIMIT子句之前。它还需要;来结束查询。