查询从一个表和一个额外的col检索信息,这是另一个表中的条件

时间:2016-01-25 16:28:55

标签: mysql sql count case

我有一张工人桌和一张相关的牌桌:

CREATE TABLE IF NOT EXISTS `workers` (
  `ID` varchar(20) NOT NULL,
  `companyID` int(11) NOT NULL,
  `FName` varchar(25) NOT NULL,
  `Sname` varchar(25) NOT NULL,
  `isAvailable` tinyint(4) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `workers`
 ADD PRIMARY KEY (`ID`), ADD KEY `cmp_idx` (`companyID`), ADD KEY `isAvailable_idx` (`isAvailable`);

我需要检索一份工人清单,每个人都有一个关于他们的卡是否未获批准的指标。

卡表如下:

CREATE TABLE IF NOT EXISTS `cards2` (
`ID` int(11) NOT NULL,
  `Name` varchar(200) NOT NULL,
  `WorkerID` varchar(20) NOT NULL,
  `pic` varchar(200) NOT NULL,
  `expDate` bigint(20) NOT NULL,
  `reminderSent` tinyint(4) NOT NULL,
  `regNum` varchar(8) NOT NULL,
  `cardType` varchar(200) NOT NULL,
  `approvalStatus` tinyint(4) NOT NULL
) ENGINE=MyISAM AUTO_INCREMENT=95 DEFAULT CHARSET=latin1;

ALTER TABLE `cards2`
 ADD PRIMARY KEY (`ID`), ADD KEY `cardsWorkerID_idx` (`WorkerID`);

approvalStatus可以是2(尚未确定),1(已批准)或2(已批准) 因此,如果所有卡都被批准,则返回的指标应为绿色(1);如果任何卡尚未批准或未批准,则返回红色(0)。

检索工人的问题很简单:

SELECT distinct Workers.ID, FName, SName, companyID
FROM Workers WHERE companyID = ? and  
and isAvailable = 1
LIMIT ?, 10

当试图取回卡片指示器时,我尝试了以下内容:

    SELECT Workers.ID, FName, SName, 
COUNT(CASE WHEN approvalStatus = 0 or approvalStatus = 2 THEN 1 ELSE 0 end) AS cardStatus 
FROM `workers` 
inner join cards2 ON Workers.ID = Cards2.WorkerID 
WHERE workers.companyID = 1

这只返回一名工人

更新 如果用户没有关联卡,它也应该标记红色状态

1 个答案:

答案 0 :(得分:0)

您可以询问EXISTS,是否存在针对用户的已打开或已拒登的卡片:

select id, fname, sname, companyid,
  case when exists 
  (
    select * 
    from cards2 c
    where c.workerid = w.id
    and c.approvalstatus in (0,2)
  ) then then 'red' else 'green' end as status
from workers w 
where companyid = ?
and isavailable = 1;

更新:以下是没有卡=红色的附加要求的查询:

select id, fname, sname, companyid,
  case when exists 
  (
    select * 
    from cards2 c
    where c.workerid = w.id
    and c.approvalstatus in (0,2)
  )
  or not exists 
  (
    select * 
    from cards2 c
    where c.workerid = w.id
  ) then then 'red' else 'green' end as status
from workers w 
where companyid = ?
and isavailable = 1;

这与使用MySQL三布尔逻辑聚合的状态相同:

select w.id, w.fname, w.sname, w.companyid,
  case when not c.bad then 'green' else 'red' end as status
from 
(
  select 
    workerid,
    max(case when approvalstatus in (0,2) then 1 else 0 end) as bad
  from cards2
  group by workerid
) c
from workers w 
where w.companyid = ? and  
and w.isavailable = 1;