假设f是一个字符串函数,例如串联0:f(0011)= 00110。
假设mytable
列string
是一个索引,price
。
我想做类似下面的伪代码:
UPDATE mytable SET price(X)=0.5 FOR ALL THOSE ROWS X SUCH THAT
THE ROW Y SUCH THAT THE `string` OF Y equals f(the `string` FOR X)
HAS price(Y)=0
更一般地说,我该如何参考
"这样的行[条件保持 - 取决于当前行]"
in(My)SQL?
答案 0 :(得分:1)
将UPDATE
与自我加入一起使用。
UPDATE mytable AS x
JOIN mytable AS y ON y.string = f(x.string)
SET x.price = 0.5
WHERE y.price = 0
答案 1 :(得分:1)
设置演示
CREATE TABLE mytable
( id INT UNSIGNED NOT NULL PRIMARY KEY
, thestring VARCHAR(32)
, price DECIMAL(11,2)
) ENGINE=INNODB
;
INSERT INTO mytable (id, thestring, price) VALUES
( 1,'0011' , 123.45)
,( 2,'00110' , 45.67)
,( 3,'001100' , 0.00)
,( 4,'10' , 4.44)
,( 5,'100' , 5.55)
,( 6,'1000' , 0.00)
;
编写一个标识mytable
中Y行的查询SELECT y.*
FROM `mytable` `y`
WHERE y.price = 0.0
ORDER BY y.id
向mytable添加联接以查找匹配的X行
SELECT x.id AS x_id
, x.thestring AS x_thestring
, x.price AS x_price
, y.id AS y_id
, y.thestring AS y_thestring
, y.price AS y_price
FROM mytable `y`
JOIN mytable `x`
ON CONCAT(x.thestring,'0') = y.thestring
WHERE y.price = 0.0
ORDER BY y.id
将SELECT转换为UPDATE。 (将SELECT ... FROM替换为UPDATE,并在WHERE子句之前添加SET子句。
UPDATE mytable `y`
JOIN mytable `x`
ON CONCAT(x.thestring,'0') = y.thestring
SET x.price = 0.5
WHERE y.price = 0.0
只需将CONCAT(x.thestring,'0')
替换为f(x.thestring)
即可。
另一个选择是使用相关子查询。
首先,写一个SELECT
SELECT x.*
FROM mytable `x`
WHERE EXISTS ( SELECT 1
FROM mytable `y`
WHERE y.thestring = f(x.thestring)
AND y.price = 0.00
)
然后将其转换为UPDATE。将SELECT ... FROM
替换为UPDATE
关键字,并在SET
子句之前添加WHERE
子句。
UPDATE mytable `x`
SET x.price = 0.5
WHERE EXISTS ( SELECT 1
FROM mytable `y`
WHERE y.thestring = f(x.thestring)
AND y.price = 0.00
)