我有两张桌子......比如块和过程
过程:
P_ID P_NAME ---- ------ 1 x1p1 2 x1p4 3 x1p8 4 x2p1 5 x3p4 6 x3py
块:
B_ID BLOCK_NAME P_ID ------ ------------------------------- ------ 1 x1p1ef......ldoddr60maew...... (null) 2 x1p4fr......ldoddr60mans...... (null) 3 x1p8jg......ldoddr80maew...... (null) 4 x1p4gh......ldoddr80mans...... (null) 5 x1p8mj......ldoyyyyy20ma...... (null) 6 x2p1ad......ldoyyyyy30maisclk.... (null) 7 x3p4da......ldoyyyyy30ma...... (null) 8 x3p4we......ldozzzzz20ma...... (null) 9 x3pxtu......ldozzzzz40ma...... (null) 10 x3pxte......ldozzzzz60ma...... (null)
Blocks表中的P_ID是引用Process表中P_ID的外键,它是主键。
现在我想更新Blocks.P_ID = Process.P_ID的值,如果Blocks.BLOCK_NAME 喜欢 Process.P_NAME
我试过
UPDATE Blocks INNER JOIN Process
ON (Blocks.BLOCK_NAME=Process.P_NAME)
SET Blocks.P_ID=Process.P_ID
WHERE Blocks.BLOCK_NAME LIKE CONCAT('%',Process.P_NAME,'%')
对于所有记录,表的Blocks.P_ID更新为1。 我把Blocks表作为:
B_ID BLOCK_NAME P_ID ------ ------------------------------- ------ 1 x1p1ef......ldoddr60maew...... 1 2 x1p4fr......ldoddr60mans...... 1 3 x1p8jg......ldoddr80maew...... 1 4 x1p4gh......ldoddr80mans...... 1 5 x1p8mj......ldoyyyyy20ma...... 1 6 x2p1ad......ldoyyyyy30maisclk.... 1
但我期待这个:
B_ID BLOCK_NAME P_ID ------ ------------------------------- ------ 1 x1p1ef......ldoddr60maew...... 1 2 x1p4fr......ldoddr60mans...... 2 3 x3p4jg......ldoddr80maew...... 5 4 x1p4gh......ldoddr80mans...... 2 5 x1p8mj......ldoyyyyy20ma...... 3 6 x2p1ad......ldoyyyyy30maisclk.... 4
我不知道我哪里出错了...有人可以帮帮我吗? 在此先感谢... !!
答案 0 :(得分:4)
你非常接近。
您应该使用ANSI连接语法并将LIKE
条件放在ON
子句中
UPDATE blocks b JOIN process p
ON b.block_name LIKE CONCAT(p.p_name, '%')
SET b.p_id = p.p_id;
或隐式逗号连接语法并将条件放在WHERE
子句
UPDATE blocks b, process p
SET b.p_id = p.p_id
WHERE b.block_name LIKE CONCAT(p.p_name, '%');
另一种方法
UPDATE blocks b JOIN process p
ON p.p_name = LEFT(b.block_name, CHAR_LENGTH(p.p_name))
SET b.p_id = p.p_id;
结果:
+------+-----------------------------------+------+ | B_ID | BLOCK_NAME | P_ID | +------+-----------------------------------+------+ | 1 | x1p1ef......ldoddr60maew...... | 1 | | 2 | x1p4fr......ldoddr60mans...... | 2 | | 3 | x1p8jg......ldoddr80maew...... | 3 | | 4 | x1p4gh......ldoddr80mans...... | 2 | | 5 | x1p8mj......ldoyyyyy20ma...... | 3 | | 6 | x2p1ad......ldoyyyyy30maisclk.... | 4 | | 7 | x3p4da......ldoyyyyy30ma...... | 5 | | 8 | x3p4we......ldozzzzz20ma...... | 5 | | 9 | x3pxtu......ldozzzzz40ma...... | NULL | | 10 | x3pxte......ldozzzzz60ma...... | NULL | +------+-----------------------------------+------+
答案 1 :(得分:0)
试试这个:
UPDATE Blocks B
INNER JOIN PROCESS P ON B.BLOCK_NAME LIKE CONCAT(P.P_NAME + '%')
SET B.P_ID=P.P_ID;