2012-09-26 77 views
2

我有這樣的(表A)數據的MySQL如果列包含

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

和這樣的(表B)

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

我想更新與該條件表乙狀況的表

如果表中的行1和2(i表示不包含「」值)一個狀態完成然後在表B中DG12狀態後...

我該怎麼做?使用php + mysql,任何人都可以幫忙嗎? 感謝前

+0

如果tableA key =「dg12」和status =「done」中的關係狀態 - >刪除tableB中的行,其中id =「dg12」? – ClydeFrog

+1

所以約束條件是表A在表B更新之前必須有兩個記錄'status'!= null? – ethrbunny

+0

@ethrbunny是這樣的... –

回答

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') 

OR

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 
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 
+0

錯! 「所以約束條件是表A在表B被更新之前必須有兩個記錄'status'!= null'...是......」 – fancyPants

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行的可能性。不確定會發生。

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; 

從上面的前查詢ecuted:

1 row affected

瞭解更多關於子查詢與ALLhere