我有这张 table 的病人,必须查询它
Update the database in order to provide a 3% discount to all patients in a room that has more than 2 patients.
表格如下:
CREATE TABLE patient (
sin varchar(20) NOT NULL,
disease varchar (20),
bed varchar (20),
room varchar (20),
hospital varchar (0),
fee varchar(20),
entry_date date NOT NULL,
exit_date date,
CONSTRAINT FOREIGN KEY (sin) REFERENCES person(sin)
)
所以我想找到所有有超过2名患者的病房,然后更新表格:
UPDATE patient C
INNER JOIN patient D ON C.sin=D.sin and D.sin IN (SELECT A.sin
FROM patient A
WHERE 2 < (SELECT COUNT(B.sin)
FROM patient B
WHERE A.hospital=B.hospital and A.room=B.room and A.exit_date IS NULL and B.exit_date IS NULL)
)
SET C.fee=C.fee*0.97
问题是我收到错误:
You can't specify target table 'C' for update in FROM clause
有没有办法将子查询与更新一起使用? 非常感谢。
最佳答案
您走在正确的道路上。 但是您想要加入房间信息,而不是患者信息。所以:
UPDATE patient p JOIN
(select hospital, room
from patient
where exit_date is null
group by hospital, room
having count(*) > 2
) r
ON p.hospital = r.hospital and p.room = r.room
SET p.fee = p.fee * (1 - 0.03)
WHERE exit_date is null;
关于MySql 使用带更新的子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40793855/