来自两个表的SQL查询

时间:2010-11-11 20:34:15

标签: sql database

我有两个表(客户,管理员)用户通过电子邮件和密码登录,我需要检查客户或管理表中是否存在电子邮件和密码。电子邮件是unquie,所以不会有问题。这是单向工作,显然我会有比这更好的数据库设计,但我必须使用给定的。 我有这个:

$email = $_POST['email']; 
$password = $_POST['password'];

$sql = "SELECT * FROM customer, admin WHERE cus_email = '$email'
 AND cus_password = '$password' OR admin_email = '$email' AND admin_password = '$password'";

对于Joins不是很好,所以我没有尝试过这个。

感谢您的帮助:)

2 个答案:

答案 0 :(得分:3)

你真的需要一个UNION而不是JOIN:

SELECT username
  FROM Customer
 WHERE cus_email = ? AND cus_password = ?
UNION
SELECT adminname AS username
  FROM admin
 WHERE admin_email = ? AND admin_password = ?

您应该使用占位符 - 问号 - 或保护自己免受SQL Injection攻击。有一些功能可以帮助您在PHP中实现这一点。

答案 1 :(得分:2)

SELECT cus_id as id, 'false' as IsAdmin 
FROM customer
WHERE cus_email = '$email' 
    AND cus_password = '$password' 
UNION ALL    
SELECT admin_id as id, 'true' as IsAdmin
FROM admin
WHERE admin_email = '$email' 
    AND admin_password = '$password'";