SQL - Check if data exists on either table

。_饼干妹妹 提交于 2019-12-02 06:54:12

Your tables don't have the same structure. You could do a UNION ALL to do the query on both tables, but only return some information for Librarians:

SELECT TOP 1 * 
FROM(
  SELECT studentId AS userID, password, firstName, LastName
  FROM tblUserStudent 
  WHERE StudentID = 'S1201235'
  UNION ALL
  SELECT LibrarianID,password, NULL, NULL
  FROM tblUserLibrarian 
  WHERE LibrarianID = 'S1201235'
) a

sqlfiddle demo (sql server, but serves as an example)

I added an alias to the id's column to show you userID instead of studentID, since UNION takes the column names from the first SELECT.

I also left the TOP 1, but if your ID's are unique, you should receive only one, making it irrelevant

select StudentID,Password,FirstName,LastName from tblUserStudent where studentID='S1202836'
union
select LibrarianID,Password,null,null from tblUserLibrarian where LibrarianID='L1202836'

I'm not sure if i understand your requirement correctly, but it seems you want a union, not a join, and since your librarian table has fewer columns than your user student table, you have to fill up with null columns so the column count matches.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!