5

我有两个表,一个捕获登录信息的登录表,以及一个将 IP 信息与国家/地区相关联的范围表。我正在尝试创建一个触发器,该触发器在插入后通过对范围表执行连接来更新 logins.country 列。

这些表的结构如下:

CREATE TABLE logins (
id int(10) unsigned NOT NULL AUTO_INCREMENT,
users_id int(10) unsigned NOT NULL,
ip int(10) unsigned NOT NULL,
country varchar(2) DEFAULT NULL,
status tinyint(4) NOT NULL,
timestamp timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE ranges (
id int(10) unsigned NOT NULL AUTO_INCREMENT,
first int(10) unsigned NOT NULL,
last int(10) unsigned NOT NULL,
country varchar(2) NOT NULL,
PRIMARY KEY (id),
UNIQUE KEY first_UNIQUE (first),
UNIQUE KEY last_UNIQUE (last)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

我有这个触发器,但它似乎不起作用:

CREATE TRIGGER update_country
AFTER INSERT ON logins
FOR EACH ROW
UPDATE logins l
JOIN ranges r ON l.ip >= first AND l.ip <= last
SET l.country = r.country
WHERE l.id = NEW.id;

知道我在哪里出错了吗?

4

1 回答 1

11

在玩了一段时间之后,我意识到加入并不是必需的,而且我让这个变得比它需要的复杂得多。这是最后的触发器:

CREATE TRIGGER update_country BEFORE INSERT
ON logins FOR EACH ROW
SET NEW.country = (SELECT country FROM ranges WHERE NEW.ip >= first AND NEW.ip <= last);
于 2013-07-04T22:32:38.020 回答