2

我的数据库中有 2 个表,一个是tablea,另一个是tableb

SELECT * 
FROM   TABLEA

结果是:

╔═════════════════════════════════════════════════════╗
║           ip                          mac           ║
╠═════════════════════════════════════════════════════╣
║         1.10.0.0.97               00 14 2A 2F 72 FE ║
║        1.10.0.0.98                08 CC 68 71 A1 C0 ║
╚═════════════════════════════════════════════════════╝



SELECT * 
FROM   TABLEB 

结果是:

╔═══════════════════════════════════════╗
║     mac                          port ║
╠═══════════════════════════════════════╣
║     0:14:2a:2f:72:fe               24 ║
║     8:cc:68:71:a1:c0                7 ║
╚═══════════════════════════════════════╝

我现在想创建第三个表,它连接 tablea 和表 c,并有 3 列显示 ip、ma​​c 和端口。该表已经创建,这就是我的想法;

INSERT INTO TABLEC 
SELECT A.IP, 
       A.MAC, 
       B.PORT 
FROM   TABLEA A, 
       TABLEB B 
WHERE  A.MAC = REPLACE('REPLACE('B.MAC',':',' ')','0','00')

查询给了我一个错误

ERROR 1064(42000): 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 'b.mac',':',' ')','0','00')

我检查了手册,但我无法确定我的错误在哪里。而且我的替换功能可以将 0:14:2a:2f:72:fe 转换为 00 14 2A 2F 72 FE,但如果尝试 8:cc:68:71:a1:c0 它将不起作用。我非常感谢我在创建第三张桌子时能得到的任何帮助

4

3 回答 3

2

您应该删除'beforereplace和 after)以及b.mac. 您也不能替换0为,00因为c0它会返回c00,您应该改用LPAD

INSERT INTO TABLEC 
SELECT A.IP, 
       A.MAC, 
       B.PORT 
FROM   TABLEA A, 
       TABLEB B 
WHERE  A.MAC = UPPER(LPAD(REPLACE(B.MAC, ':', ' '), 17, '0')) 

SQL 小提琴演示

于 2013-09-11T07:21:58.677 回答
2

在进行替换之前,您应该 lpad (with 0) tableb.mac。

于 2013-09-11T07:24:38.077 回答
2
INSERT INTO tablec
SELECT a.ip, a.mac, b.port
FROM tablea a 
LEFT JOIN tableb b 
ON a.mac = upper(LPAD(replace(b.mac,':',' '),17,'0'))

parado 的替换比我写的更有意义 -

于 2013-09-11T07:44:30.063 回答