2

我有一张这样的数据表(表 A)

id | key  | status
-----------------
1  | dg12 | done
2  | dg12 | 

像这样(表B)

id   | Name  | status
------------------
dg12 | Dummy | 

我想用这个条件更新表 B 的状态

如果第 1 行和第 2 行中的表 A 状态(我的意思是不包含“”值)已完成,则表 B 中的 dg12 状态已完成...

我怎样才能做到这一点??使用php + mysql,任何人都可以帮忙吗?谢谢之前

4

4 回答 4

1
Update tableA a,tableb b
SET b.status=CASE WHEN (select count(*) from tableB where id=a.key group by key,status) > 0 then 'Done' else b.status end
where a.key=b.id
于 2012-09-26T12:44:49.123 回答
1
UPDATE 
    tableB AS b
SET 
    b.status = 'done'
WHERE 
    (SELECT COUNT(*) FROM tableA AS a WHERE a.key = b.id) 
    = 
    (SELECT COUNT(*) FROM tableA AS a WHERE a.key = b.id AND a.status = 'done')

或者

UPDATE 
    tableB AS b
SET 
    b.status = 'done'
WHERE 
    (SELECT COUNT(*) FROM tableA AS a WHERE a.key = b.id AND a.status != 'done') = 0
于 2012-09-26T12:48:02.350 回答
1

它可以更短:

UPDATE tableB b
SET b.`status` = 'done'
WHERE 'done' = ALL(SELECT `status` FROM tableA a WHERE a.key = b.id)

测试数据在这里:

drop table if exists tableA;
create table tableA(id int, `key` varchar(10), status varchar(10));
insert into tableA values (1, 'dg12', 'done'), (2,'dg12', '');
drop table if exists tableB;
create table tableB(id varchar(10), name varchar(10), status varchar(10));
insert into tableB values ('dg12','Dummy', '');

从上面执行的查询:

0 rows affected

update tableA set status='done' where id = 2;

从上面执行的查询:

1 row affected

ALL 在此处阅读有关子查询的更多信息。

于 2012-09-26T12:59:45.963 回答
0
SELECT
   TRUE
FROM
   tableA
WHERE
   key = ?
   AND status <> 'done'
LIMIT 1
...
// all tableA for key="dg12" are "done"
if (!$query->execute("dg12")->num_rows()) {
   UPDATE tableB SET status = "done" WHERE id = ?
   ...
   $query->execute("dg12");
}

如果您不明白,请告诉我,因为这主要是伪 php。

这也没有考虑到 tableA 在该键上不包含任何行的可能性。不确定这是否会发生。

于 2012-09-26T12:48:37.867 回答