禁止在MySQL的更新子句中使用相同的目標表
P粉982009874
P粉982009874 2024-04-02 10:49:18
0
1
279

我有一個名為「employee」的表。表格建立程式碼如下:

create table employee(name varchar(50),ph_no varchar(10),e_id varchar(5),pay_scale varchar(5),year varchar(4));

表格內容如下:

insert into employee(name,ph_no,pay_scale,year) values('AMIT','123456','PL-10','2019');
insert into employee(name,ph_no,pay_scale,year) values('AMIT','123456','PL-10','2020');
insert into employee(name,ph_no,pay_scale,year) values('AMIT','123456','PL-11','2021');
insert into employee(name,ph_no,pay_scale,year) values('AMIT','123456','PL-11','2022');

+------+--------+------+-----------+------+
| name | ph_no  | e_id | pay_scale | year |
+------+--------+------+-----------+------+
| AMIT | 123456 | NULL | PL-10     | 2019 |
| AMIT | 123456 | NULL | PL-10     | 2020 |
| AMIT | 123456 | NULL | PL-11     | 2021 |
| AMIT | 123456 | NULL | PL-11     | 2022 |
+------+--------+------+-----------+------+

現在我想更新'e_id',首先它會檢查表中是否有相同的e_id,如果不在表中那麼它只會更新給定e_id的行,否則不會要去更新了。 因此,我的升級查詢如下:

update employee 
set e_id='0132' 
where concat_ws(',',name,ph_no,pay_scale)=concat_ws(',','AMIT','123456','PL-10') 
  and not exists (select e_id 
                  from employee 
                  group by e_id 
                  having count(*)>=1);

但它給了以下錯誤:

錯誤 1093 (HY000):您無法在 FROM 子句中指定要更新的目標表“employee” 我嘗試過以下查詢:

update employee set e_id='0132' where
concat_ws(',',name,ph_no,pay_scale)=concat_ws(',','AMIT','123456','PL-10') and 
e_id not in 
    (select e_id from 
    (select e_id from employee group by e_id having count(*)>=1) as t);

但這也無法更新表格並顯示以下結果:

Query OK, 0 rows affected (0.01 sec)
匹配的行:0 更改:0 警告:0

也嘗試了以下程式碼:

update employee set 
employee.e_id='0132' where 
employee.e_id not in (select * from
    (select f.e_id from 
    employee f inner join employee b on 
    b.name=f.name and b.ph_no=f.ph_no and b.pay_scale=f.pay_scale) as tmp) 
and employee.name='AMIT' and employee.ph_no='123456' and employee.pay_scale='PL-10';

但這也無法更新表格並給出以下結果: 查詢正常,0 行受影響(0.00 秒) 符合的行:0 更改:0 警告:0 請幫忙。預先感謝您。

P粉982009874
P粉982009874

全部回覆(1)
P粉604669414

NULL 的播放方式與某些人期望的NOT IN 不同:https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=24c176ff4d4e2c52309aaca14cc121c5 因此,只需將WHERE e_id IS NOT NULL 放在子中詢問。另外,HAVING COUNT(*) >= 1 可以刪除,因為它總是會傳回 1 或更多的值...

update
  employee
set
  e_id='0132'
where
     name      = 'AMIT'
 and ph_no     = '123456'
 and pay_scale = 'PL-10'
 and e_id      not in (select e_id from 
                        (select distinct e_id
                           from employee
                          where e_id IS NOT NULL
                        )
                        as t
                       );

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=2a0b036a7d1db9138e3ab29af3d346f8 一个>

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!