1

我有三个safe_workers, safe_companies and safe_customers用于存储不同帐户类型的表。登录后,我需要一个查询来查找所有三个表中的 LoginEmail 和 LoginPassword 列,并根据登录页面传递的登录表单返回匹配项。

我是 MySQL 的初学者并尝试了以下方法,但显然它返回了一个错误。

select safe_companies.LoginEmail,ID 
from safe_companies,safe_customers 
WHERE LoginEmail='.$_POST[InEmail].' AND LoginPass= '.$_POST[InPass].'

我不想比较表只是想匹配

4

3 回答 3

0

我根据您的问题详细信息做出一个假设,即特定用户的 LoginEmail 和 LoginPass 值将仅存在于三个表之一中。如果是这种情况,您可以使用如下所示的 UNION。

SELECT a.LoginEmail, a.ID
FROM (
    SELECT LoginEmail, ID FROM safe_workers
    UNION
    SELECT LoginEmail, ID FROM safe_companies
    UNION
    SELECT LoginEmail, ID FROM safe_customers
) AS a
WHERE a.LoginEmail = 'InEmail' AND a.LoginPass= 'InPass';

但是,这可能会导致各种不良情况。

于 2013-03-12T20:37:39.340 回答
0

如果我很好地理解了您的问题:

您正在寻找的是http://dev.mysql.com/doc/refman/5.0/en/join.html

如果两个表都有一个名为 LoginEmail 的列。

SELECT
    sco.LoginEmail
FROM
   safe_companies AS sco
INNER JOIN
    safe_customers AS scu ON (sco.LoginEmail = scu.LoginEmail)
WHERE
    sco.LoginEmail = '" . $_POST['InEmail'] . "' AND
    scu.LoginPass = '" . $_POST['InPass'] . "'

如果没有,请提供更多信息,例如表结构。

于 2013-03-12T20:05:12.390 回答
0

您可以使用该UNION语句来完成此操作。尝试这个:

$dbh = new PDO('...');

$where = 'WHERE LoginEmail = :email AND LoginPass = :pass';
$query = [];
foreach (['safe_workers', 'safe_companies', 'safe_customers'] as $table) {
    $query[] = "(SELECT LoginEmail, ID FROM {$table} {$where})";
}

/*
 * This will become something like this:
 * (SELECT LoginEmail, ID FROM safe_workers WHERE LoginEmail = :email AND LoginPass = :pass)
 * UNION
 * (SELECT LoginEmail, ID FROM safe_companies WHERE LoginEmail = :email AND LoginPass = :pass)
 * UNION
 * (SELECT LoginEmail, ID FROM safe_customers WHERE LoginEmail = :email AND LoginPass = :pass)
 */
$stmt = $dbh->prepare(implode(' UNION ', $query));

$stmt->bindParam(':email', $_POST['inEmail']);
$stmt->bindParam(':pass', $_POST['inPass']);
if ($stmt->execute()) {
    var_dump($stmt->fetch(PDO::FETCH_ASSOC));
}

注意:我使用 PDO 来准备语句并转义 POST 数据。看看它的手册

于 2013-03-12T20:06:06.223 回答