使用INNER JOIN从两个表中删除数据

时间:2013-12-22 09:54:13

标签: php sql inner-join

我想根据datetime_lastactive从一个SQL查询中删除两个表中的数据,以及IP地址是否与您自己的匹配。但是当我尝试以下SQL查询时,我收到此错误消息:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 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 'INNER JOIN visitors_main WHERE information_ipaddress = '123.123.123.123' A' at line 2' in ...

DELETE FROM visitors_list
INNER JOIN visitors_main
WHERE information_ipaddress = :ipaddress
AND datetime_lastactive < NOW() - INTERVAL 3 HOUR

表格如下:

CREATE TABLE IF NOT EXISTS `visitors_list` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `id_visitor` int(10) DEFAULT '0',
  `id_user` int(10) DEFAULT '0',
  `data_filename` text NOT NULL,
  `data_filename_get` text NOT NULL,
  `data_useragent` text NOT NULL,
  `datetime_lastactive` datetime NOT NULL,
  `information_ipaddress` text NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id` (`id`)
)

CREATE TABLE IF NOT EXISTS `visitors_main` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `id_user` int(10) DEFAULT '0',
  `data_coordinates` varchar(25) NOT NULL,
  `datetime_firstvisit` datetime NOT NULL,
  `checkbox_anonymous` tinyint(4) DEFAULT '0',
  `checkbox_tiecoordinates` tinyint(4) DEFAULT '0',
  `checkbox_nogps` tinyint(4) DEFAULT '0',
  `information_ipaddress` text NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id` (`id`)
)

我该如何做到这一点?

2 个答案:

答案 0 :(得分:1)

请改为尝试:

DELETE l, m
FROM visitors_list AS l
INNER JOIN visitors_main AS m ON l.information_ipaddress = m.information_ipaddress
WHERE l.information_ipaddress = :ipaddress
AND l.datetime_lastactive < NOW() - INTERVAL 3 HOUR;

答案 1 :(得分:0)

DELETE v1,v2
FROM visitors_list v1
INNER JOIN visitors_main v2 ON v1.id_visitor = v2.id
WHERE v1.information_ipaddress = :ipaddress
AND v1.datetime_lastactive < NOW() - INTERVAL 3 HOUR;