英文:
find who the manager using boolean datatype(true, false) in ismanager column
问题
以下是翻译好的部分:
"create table usertable (
empid int primary key,
empname varchar(40),
position varchar(40),
managerid int,
foreign key (managerid) references usertable(empid),
ismanager bit(1)
);"
"update usertable set ismanager=
case
when empid in (select managerid from usertable) then 1
else 0
end;"
英文:
There are set of data listed under table employee like empid, empname, position, managerid, ismanager.
Here some employees are manager and some not. If that employee is manager it has to show 1 in ismanager column, if that employee is not manager it has to show 0 in ismanager column, if empid is listed in managerid then ismanager should be updated to 1 else it should be 0.
create table usertable (
empid int primary key,
empname varchar(40),
position varchar(40),
managerid int,
foreign key (managerid) references usertable(empid),
ismanager bit(1)
);
This is what I have tried:
update usertable set ismanager=
case
when empid in (select managerid from usertable) then 1
else 0
end;
答案1
得分: 0
以下是已翻译的内容:
如果它们都当前设置为0
,则只需要更新那些是管理者的人:
UPDATE usertable u1
JOIN (SELECT DISTINCT managerid FROM usertable WHERE managerid IS NOT NULL) u2
ON u1.empid = u2.managerid
SET u1.ismanager = 1;
如果它们都设置为null
,并且您需要同时设置1
和0
:
UPDATE usertable u1
LEFT JOIN (SELECT DISTINCT managerid FROM usertable WHERE managerid IS NOT NULL) u2
ON u1.empid = u2.managerid
SET u1.ismanager = (u2.managerid IS NOT NULL);
当然,您可以放弃冗余的ismanager
列,并动态检索它:
SELECT *, EXISTS (SELECT 1 FROM usertable WHERE managerid = u.empid) AS ismanager
FROM usertable u;
英文:
As they are all set to 0
currently, you only need to update the ones who are managers:
UPDATE usertable u1
JOIN (SELECT DISTINCT managerid FROM usertable WHERE managerid IS NOT NULL) u2
ON u1.empid = u2.managerid
SET u1.ismanager = 1;
If they are all set to null and you need to set both the 1
s and 0
s:
UPDATE usertable u1
LEFT JOIN (SELECT DISTINCT managerid FROM usertable WHERE managerid IS NOT NULL) u2
ON u1.empid = u2.managerid
SET u1.ismanager = (u2.managerid IS NOT NULL);
Of course, you could ditch the redundant ismanager
column and retrieve it dynamically:
SELECT *, EXISTS (SELECT 1 FROM usertable WHERE managerid = u.empid) AS ismanager
FROM usertable u;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论