SQL使用不同的列连接2个表

时间:2017-11-08 11:07:12

标签: sql ms-access

我正在尝试为2个表中存在的用户名和密码创建单个登录函数。 目前我有

SELECT * FROM CUSTOMER WHERE username = usernameIN AND password = passwordIN
SELECT * FROM STAFF WHERE username = usernameIN AND password = passwordIN

如果匹配,则登录用户。

是否存在连接这两个表的查询,因此我可以对它们运行1个SQL查询。

输入表格

CUSTOMER
username,password,firstname,lastname,addressline1,town

andys,pass123,andy,smith,123 fake st,fake town

STAFF
username,password,firstname,lastname,position,salary

davidq,pass321,david,queen,manager,10000

SQL查询的预期输出

OUTPUT TABLE   
username,password,firstname,lastname,addressline1,town,position,salary

andys,pass123,andy,smith,123 fake st,fake town,null,null
davidq,pass321,david,queen,null,null,manager,10000

4 个答案:

答案 0 :(得分:4)

您需要UNION ALL

SELECT username,
       password1,
       firstname,
       lastname,
       addressline1,
       town,
       NULL AS manager,
       NULL AS salary
FROM customer
UNION ALL
SELECT username,
       password1,
       firstname,
       lastname,
       NULL,
       NULL,
       POSITION,
       salary
FROM staff;

您可以相应地将WHERE条款添加到您的个人查询中。

如果您想避免重复行,请使用UNION

<强>结果:

username    password1   firstname   lastname    addressline1    town            manager     salary
--------------------------------------------------------------------------------------------------
andys       pass123     andy        smith       123 fake st     fake town       NULL        NULL
davidq      pass321     david       queen       NULL            NULL            manager     10000

<强> DEMO

答案 1 :(得分:1)

SELECT 
  username,password,firstname,lastname,addressline1,town, null as position, null as salary
FROM
  CUSTOMER  
WHERE username = usernameIN AND password = passwordIN  
UNION ALL  
SELECT  
  username,password,firstname,lastname, null, null, position,salary  
FROM  
  STAFF  
WHERE username = usernameIN AND password = passwordIN  

您必须添加别名

答案 2 :(得分:1)

您可以使用UNION加入表格,如下所示。

SELECT username, password, firstname, lastname, addressline1, town, position, salary FROM 
(SELECT username, password, firstname, lastname, addressline1, town, null position, null salary FROM CUSTOMER
UNION ALL
SELECT username, password, firstname, lastname, null addressline1, null town, position,salary FROM STAFF) AS t
WHERE t.username = 'username' AND t.password = 'password'

答案 3 :(得分:0)

使用UNION

SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;