我有两个表tblteacher和tblattendance共有tshortname字段。现在我想显示来自tblteacher的tshortname和状态为'yes'如果tblattendance中的特定日期我在tblattendance中也有tshortname否则状态应为'no'< / p>
select distinct(tblteacher.teachername),tblteacher.tshortname,
if(strcmp(tblteacher.tshortname,tblattendance.tshortname) and tblattendance.attdate='2013-07-01','no','yes') as status
from tblteacher,tblclass,tblattendance
这是我执行上述查询时显示的数据
显示日期 - '2013-07-01'的数据对于某些老师来说是正确的。我没有得到问题所在。请帮我解决这个问题
更新
select distinct(tblteacher.tshortname),if (tblteacher.tshortname not in(SELECT
distinct(t.tshortname) from tblteacher t left join tblattendance a on t.tshortname=a.tshortname
where a.attdate='2013-07-03'),'no','yes') as status from tblteacher;
现在我总是根据就勤表中的日期获得42行和正确的状态
答案 0 :(得分:1)
你在这里有一个表之间的经典笛卡尔连接。
您需要告诉数据库如何匹配各种表中的数据,如下所示:
select distinct
(tblteacher.teachername),tblteacher.tshortname,
if(strcmp(tblteacher.tshortname,tblattendance.tshortname) and tblattendance.attdate='2013-07-01','no','yes') as status
from
tblteacher
join tblclass
on tblteacher.tshortname=tblattendance.tshortname
join tblattendance
on tblteacher.tshortname=tblattendance.teacherShortName
在你的情况下,strcpm将处理前两个中的连接,但会将它与第三个表中的所有行匹配 - 这是你出错的地方。
编辑:根据您的评论,这可能会更好地让您按预期获得所有行。
select distinct
(tblteacher.teachername),tblteacher.tshortname,
if(strcmp(tblteacher.tshortname,tblattendance.tshortname) and tblattendance.attdate='2013-07-01','no','yes') as status
from
tblteacher
left outer join tblclass
on tblteacher.tshortname=tblattendance.tshortname
left outer join tblattendance
on tblteacher.tshortname=tblattendance.teacherShortName
答案 1 :(得分:0)
您需要离开加入考勤表,然后
select if(tblattendance.tshortname is not null and attdate = '2013-07-01', 'yes', 'no') as status
修改:完整查询
SELECT DISTINCT
t.tshortname,
teachername,
IF(attdate = '2013-07-01','yes','no') AS status
FROM tblteacher AS t
LEFT JOIN tblattendance AS a
ON t.tshortname = a.tshortname
答案 2 :(得分:0)
只是一个猜测......
SELECT DISTINCT t.tshortname
, CASE WHEN a.shortname IS NULL THEN 'no' ELSE 'yes' END status
FROM tblteacher t
LEFT
JOIN tblattendance a
ON t.tshortname = a.tshortname
AND a.attdate = '2013-07-03';