找出使用布尔数据类型(true、false)在“ismanager”列中的经理。

huangapple go评论48阅读模式
英文:

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)
);

找出使用布尔数据类型(true、false)在“ismanager”列中的经理。

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,并且您需要同时设置10

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 1s and 0s:

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;

huangapple
  • 本文由 发表于 2023年2月19日 22:32:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/75500841.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定