正如标题所示,我正在尝试使用单个查询来更新多个行,在两个不同的表中,其中id等于来自第三个表的select的结果。以下是样本表布局。
CREATE TABLE hampster_families (
id INT(13) NOT NULL AUTO_INCREMENT,
family_name varchar(255) NOT NULL UNIQUE,
fuzzy_name varchar(255),
tags varchar(255),
date_added TIMESTAMP NOT NULL DEFAULT NOW(),
PRIMARY KEY (id)
CREATE TABLE apple_addresses (
id INT(13) NOT NULL AUTO_INCREMENT,
address VARCHAR(39) NOT NULL UNIQUE,
monitor BOOLEAN NOT NULL DEFAULT 0,
date_added TIMESTAMP NOT NULL DEFAULT NOW(),
hampster_family int(7) NOT NULL DEFAULT 0,
PRIMARY KEY (id)
CREATE TABLE orange_addresses (
id INT(13) NOT NULL AUTO_INCREMENT,
address varchar(200) NOT NULL UNIQUE,
monitor BOOLEAN NOT NULL DEFAULT 0,
date_added TIMESTAMP NOT NULL DEFAULT NOW(),
hampster_family INT(7) NOT NULl DEFAULT 0,
PRIMARY KEY (id)
我正在尝试将orange_addresses.monitor,apple_addresses.monitor更新为等于1,其中orange_addresses.hampster_family,apple_addresses.hampster_family等于从SELECT id FROM hampster_families返回的id WHERE hampster_fammilies.family_name =“African Rabid”
我已经看过使用存储过的变量了,但是(我在这里缺乏SQL实力),因为这个查询需要一个变量,我不认为存储的变量会起作用。鉴于此,我已经考虑使用连接来实现这一点,但我从根本上误解了UPDATE / JOIN组合的语法。因此,我在这里寻找一些启示! :)
答案 0 :(得分:2)
一步一步: 这是您的基本查询:
SELECT id
FROM hampster_families
WHERE hampster_fammilies.family_name = "African Rabid"
现在,你想要所有orange_addresses,其中orange_addresses.hampster_family是那个id,所以,JOIN:
SELECT hampster_families.id
FROM hampster_families
LEFT JOIN orange_adresses
ON orange_addresses.hampster_family = hampster_families.id
WHERE hampster_fammilies.family_name = "African Rabid"
apple_addresses也是如此:
SELECT hampster_families.id
FROM hampster_families
LEFT JOIN orange_adresses
ON orange_addresses.hampster_family = hampster_families.id
LEFT JOIN apple_adresses
ON apple_addresses.hampster_family = hampster_families.id
WHERE hampster_fammilies.family_name = "African Rabid"
我们对他们的监视列感兴趣
SELECT orange_addresses.monitor, apple_addresses.monitor
FROM hampster_families
LEFT JOIN orange_adresses
ON orange_addresses.hampster_family = hampster_families.id
LEFT JOIN apple_adresses
ON apple_addresses.hampster_family = hampster_families.id
WHERE hampster_fammilies.family_name = "African Rabid"
使其更新:在设置后移动所选字段,使SELECT FROM UPDATE:
UPDATE hampster_families
LEFT JOIN orange_adresses
ON orange_addresses.hampster_family = hampster_families.id
LEFT JOIN apple_adresses
ON apple_addresses.hampster_family = hampster_families.id
SET
orange_addresses.monitor = 1
apple_addresses.monitor = 1
WHERE hampster_fammilies.family_name = "African Rabid"
答案 1 :(得分:1)
这对我有用。刚检查过。
UPDATE orange_addresses, apple_addresses
SET orange_addresses.monitor=1,apple_addresses.monitor=1
WHERE orange_addresses.hampster_family = apple_addresses.hampster_family
AND orange_addresses.id = (
SELECT id
FROM hampster_families
WHERE hampster_families.family_name = 'Test'
LIMIT 1);