簡體   English   中英

如何使用 select 和同一張表上的 where 子句更新 sql 中的某些列?

[英]How to update certain column in sql using select and where clause on the same table?

我有一個名為employeepostinghistory的表,其中包含以下列:employee_posting_id、employee_posting_to、employee_posting_from、emp_emp_cnic

employee_posting_id是主鍵, emp_emp_cnic是外鍵

基本上,該表負責保存員工的歷史記錄,包括起止日期,即employee_posting_from 和employee_posting_to。

我想更新所有記錄設置employee_posting_to=NULL 在員工歷史最新的地方,我在employee_posting_from 上使用了DESC。 但是,UPDATE 查詢說子查詢返回超過 1 條記錄,這個問題的可能解決方案是什么。

UPDATE employeepostinghistory 
SET employeepostinghistory.posting_to=NULL 
WHERE employeepostinghistory.emp_emp_cnic=(
    SELECT DISTINCT employeepostinghistory.emp_emp_cnic 
    from employeepostinghistory  
    GROUP BY employeepostinghistory.emp_emp_cnic 
    ORDER BY employeepostinghistory.posting_from DESC
    )
;
UPDATE employeepostinghistory 
NATURAL JOIN ( 
    SELECT emp_emp_cnic, MAX(datetime_column) datetime_column
    FROM employeepostinghistory 
    GROUP BY 1 
    ) last_row_per_employee
SET employeepostinghistory.posting_to=NULL 
;

emp_emp_cnic.datetime_column必須是唯一的。

暫無
暫無

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

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