我一直在环顾四周,发现了很多类似的问题,但答案似乎并不是我想要的。
我网站上的注册过程如下:
_unverified
表格_unverified
转移到_verified
因此,当用户尝试创建帐户时,我必须查询两个表以确保电子邮件尚未使用。我总是单独完成这个,如下所示,这显然会使脚本膨胀。
$statement = $connect->prepare("SELECT account_email FROM users_unverified WHERE account_email = :account_email");
$statement->bindParam(":account_email", $_POST["email"]);
$statement->execute();
$result = $statement->fetch(PDO::FETCH_ASSOC);
if ($result["account_email"]) // verification process is already active or has expired
$statement = $connect->prepare("SELECT account_email FROM users_verified WHERE account_email = :account_email");
$statement->bindParam(":account_email", $_POST["email"]);
$statement->execute();
$result = $statement->fetch(PDO::FETCH_ASSOC);
if ($result["account_email"]) // account already exists
值得注意的是,$_POST["email"]
将位于一个表中,或者位于另一个表中,或者两者都不存在。
在我发现的类似问题中,人们建议使用JOINS
和UNIONS
。但是,在阅读了每种方法之后,我不相信JOINS
和UNIONS
是我正在寻找的,因为我不想将行或结果集合起来( 除非我当然能够确定该值位于哪个表中? )。
简单地说,我希望能够使用单个预准备语句查询两个表,但是如果它确实位于其中一个表中,则仍然能够确定该值位于哪个表中。我想象一下我在this question中遇到过的事情,但是,我再也不相信你能够确定价值在哪个特定的表格中。
$statement = $connect->prepare("SELECT account_email FROM users_unverified, users_verified WHERE account_email = :account_email");
有没有办法合并这些查询,同时仍然能够识别该值存在于哪个特定表中?
答案 0 :(得分:1)
你可以试试这个。
SELECT account_email, 'users_unverified' AS tablename FROM users_unverified WHERE account_email = :account_email
UNION
SELECT account_email, 'users_verified' AS tablename FROM users_verified WHERE account_email = :account_email;
答案 1 :(得分:0)
SELECT account_email, true AS verified FROM users_unverified WHERE account_email = :account_email
UNION
SELECT account_email, false AS verified FROM users_verified WHERE account_email = :account_email;