嘿伙计们我实际上对mysql开发很新....我有一个表设置..我只需要在mysql中返回最后更新的值。
所以我已经研究了更多关于它的内容,我得到了一个解决方案来为此目的创建一个触发器。
所以我的代码看起来像
CREATE TABLE CUSTOMERS(
ID INT NOT NULL AUTO_INCREMENT ,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1,'aff',2,3,5),
(2,'lolyeah',9,13,15);
触发器看起来像
CREATE TRIGGER getrandom
AFTER UPDATE ON CUSTOMERS
FOR EACH ROW
BEGIN
UPDATE CUSTOMERS
SET NAME = 'somerange'
WHERE ADDRESS = 3;
select NAME
END;
上面的触发器实际上没有用..
我需要的是当我更新CUSTOMERS列时,我需要返回最新的更新值。
希望你们能帮助我......谢谢
答案 0 :(得分:3)
代码{
sql:
CREATE TABLE CUSTOMERS(
ID INT NOT NULL AUTO_INCREMENT ,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
Date_Modified date,
PRIMARY KEY (ID)
);
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY,Date_Modified)
VALUES (1,'aff',2,3,5,'2012-11-10'),
(2,'lolyeah',9,13,15,'2014-11-10');
SELECT * FROM CUSTOMERS ORDER BY Date_Modified ASC LIMIT 1;
sql no id:
CREATE TABLE CUSTOMERS(
ID INT NOT NULL AUTO_INCREMENT ,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
Date_Modified date,
PRIMARY KEY (ID)
);
INSERT INTO CUSTOMERS (,NAME,AGE,ADDRESS,SALARY,Date_Modified)
VALUES ('aff',2,3,5,'2012-11-10'),
('lolyeah',9,13,15,'2014-11-10');
SELECT * FROM CUSTOMERS ORDER BY Date_Modified ASC LIMIT 1;
}
答案 1 :(得分:0)
我不确定你想要什么,但要使触发器工作:
CREATE TABLE CUSTOMERS(
ID INT NOT NULL AUTO_INCREMENT ,
NAME VARCHAR (20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR (25) ,
SALARY DECIMAL (18, 2),
PRIMARY KEY (ID)
);
CREATE TRIGGER `updcustomer` BEFORE UPDATE ON `CUSTOMERS`
FOR EACH ROW IF NEW.ADDRESS = 3 THEN
SET NEW.NAME = 'somerange';
END IF
尝试
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1,'aff',2,3,5),
(2,'lolyeah',9,13,15);
UPDATE CUSTOMERS SET ADDRESS=3 WHERE ID=2
第二行的名称将更改为“某个范围”
在您更新行之后,而不是在您插入行之后,将触发此触发器。对于INSERT,相应地更改触发器(UPDATE - > INSERT)
要获取最后更新的行添加:
ALTER TABLE CUSTOMERS
ADD lastmodified TIMESTAMP
DEFAULT CURRENT_TIMESTAMP
ON UPDATE CURRENT_TIMESTAMP;
并获取最新更新的ID:
SELECT ID FROM CUSTOMERS ORDER BY lastmodified DESC LIMIT 1;
此外,您应该考虑将ID字段作为主键。