簡體   English   中英

根據其他兩個表的記錄更新表

[英]Update a table according records of two other tables

我創建了相應的表:

CREATE TABLE IF NOT EXISTS StatusTable( 
    form_num INT not null auto_increment,  
    status VARCHAR(20) NOT NULL,
    primary key (form_num),
    FOREIGN KEY Status(form_num) REFERENCES Requests(reg_num)

CREATE TABLE IF NOT EXISTS Requests( 
    reg_num INT not null auto_increment, 
    ama VARCHAR(20) NOT NULL, 
    afm VARCHAR(9) NOT NULL, 
    description VARCHAR(100) NOT NULL, 
    est_cost FLOAT NOT NULL,
    primary key(reg_num),
    FOREIGN KEY Requests(afm) REFERENCES Citizens(afm)

CREATE TABLE IF NOT EXISTS Tax_data( 
    afm VARCHAR(9) NOT NULL primary key,
    ama VARCHAR(20) NOT NULL

現在,我想從表StatusTable中選擇具有特定狀態值的行。

從這些記錄中,如果afm,ama同時存在於兩個表Requests和Tax_data中,則狀態為有效,否則,如果它們僅存在於Requests中,而不存在於Tax_data中,則狀態無效。

例如:

StatusTable |   Requests |  Tax_data |
1  pending  | 1 01 001...|   01 001  |
2  valid    | 2 02 002...|   02 002  |
3  invalid  | 3 03 003...|   03 004  |
4  pending  | 4 04 004...|   04 008  |

我想從StatusTable選擇(1名待定),(4,待定),如果(1 01 001)的要求是一樣的,從Tax_data(01 001)從掛起來有效改變現狀。 如果與( 04 008 )的(4 04 004 )不同,則將狀態從待定更改為無效。

我該如何使用php和mysql? 有任何想法嗎? 我感到有點復雜。

如果我正確理解了您的問題,則可以將outer joincase語句一起使用以確定新狀態:

select r.reg_num, s.status, r.ama, r.afm, t.ama, t.afm,
       case when t.afm is not null then 'Valid' 
            else 'Invalid'  
       end newstatus
from statustable s
    join requests r on s.form_num = r.req_num
    left join tax_data t on t.ama = r.ama and t.amf = r.amf
where s.status = 'Pending'

如果隨后需要更新status表,則該方法應該起作用:

update statustable s
join requests r on s.form_num = r.req_num
left join tax_data t on t.ama = r.ama and t.amf = r.amf
set s.status = 
       case when t.afm is not null then 'Valid' 
            else 'Invalid'  
       end
where s.status = 'Pending'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM