希望从UserName
获取所有UsersDataTbl
并从UserName
匹配EnrollmentsTbl
(如果存在)。但我想确定EnrollmentsTbl
中存在哪些,而不是创建2条记录。也许添加一个布尔表达式,如果存在则获得1
,如果不存在,则添加0
。
我的SQL只返回EnrollmentsTbl
SELECT u.UserName
, e.Completed
FROM UsersDataTbl u
LEFT
JOIN EnrollmentsTbl e
ON u.UserName = e.UserName
WHERE e.ClassName LIKE 'Word%'
AND u.UserName LIKE 'bar%'
其他问题:
(SELECT u.UserName, u.LastName, d.Station
, (e.UserName IS NOT NULL) as completedl
FROM UsersDataTbl u
LEFT
JOIN EnrollmentsTbl e
ON u.UserName = e.UserName
AND e.ClassName LIKE 'Word%')
INNER JOIN UsersDataCareerTbl d
ON u.UserName = d.UserName
WHERE u.Career = 1 AND Active = 1 ORDER BY u.LastName
答案 0 :(得分:1)
您可以is not null
来测试字段的值是否为null并返回true或false。如果EnrollmentsTbl
中不存在用户名,则左连接将在其位置返回null
。
我将e.ClassName LIKE 'Word%
条件从where
子句移到了连接条件,因为它将left join
更改为inner join
,从而破坏了查询的整个目的。< / p>
SELECT u.UserName
, (e.UserName IS NOT NULL) as user_exists_in_EnrollmentsTbl
FROM UsersDataTbl u
LEFT
JOIN EnrollmentsTbl e
ON u.UserName = e.UserName
AND e.ClassName LIKE 'Word%'
WHERE u.UserName LIKE 'bar%'