获取第一个tbl中的所有记录并在第二个tbl中匹配(表示存在的记录)

时间:2017-02-18 20:54:22

标签: mysql

希望从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

1 个答案:

答案 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%'