SQL - Check if data exists on either table

前端 未结 2 1540
不思量自难忘°
不思量自难忘° 2021-01-24 14:47

I have two tables in my database regarding the login details for both of my users (Librarians and Students) I have separated the user\'s details into 2 separate tables tblUserLi

相关标签:
2条回答
  • 2021-01-24 15:42

    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

    0 讨论(0)
  • 2021-01-24 15:43
    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.

    0 讨论(0)
提交回复
热议问题