如果列包含mysql

时间:2012-09-26 12:38:01

标签: php mysql

我有一个包含这样数据的表(表A)

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

并且像这样(表B)

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

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

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

我该怎么做?使用php + mysql,任何人都可以帮忙吗?

之前谢谢

4 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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 here了解有关子查询的详情。

答案 3 :(得分: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在该键上包含 no 行的可能性。不确定是否会发生。