我从我的代码中提取了这个片段,因为我担心有更好的方法可以做到这一点。我希望有人可以帮助我或指出我正确的方向。
基本上这个代码会检查数据库中的多个表,并检查结果是否返回。
$stmt = $conn->prepare('SELECT email FROM 1table WHERE email = :email');
$stmt = $conn->prepare('SELECT email FROM 2table WHERE email = :email');
$stmt = $conn->prepare('SELECT email FROM 3table WHERE email = :email');
$stmt->bindParam(':email', $email);
$stmt->execute();
if($stmt->fetch(PDO::FETCH_NUM) > 0){
有更好的方法吗?或者更有效率的方式,可以告诉我结果在哪个表中找到了?
答案 0 :(得分:1)
它是有效的PHP,但你的逻辑无效:
$stmt = $conn->prepare('SELECT email FROM 1table WHERE email = :email');
$stmt = $conn->prepare('SELECT email FROM 2table WHERE email = :email');
$stmt = $conn->prepare('SELECT email FROM 3table WHERE email = :email');
您继续使用新值覆盖$stmt
。这意味着$stmt
将只包含最后一个准备语句。
您可以查看UNION
并修改您的代码,如下所示:
$sql = '(SELECT email FROM 1table WHERE email = :email)';
$sql .= 'UNION ALL';
$sql .= '(SELECT email FROM 2table WHERE email = :email)';
$sql .= 'UNION ALL';
$sql .= '(SELECT email FROM 3table WHERE email = :email)';
$stmt = $conn->prepare($sql);
答案 1 :(得分:1)
这只会使用最后一个查询。你可以这样做:
$stmt = $conn->prepare('
(SELECT email FROM 1table WHERE email = :email)
union all
(SELECT email FROM 2table WHERE email = :email)
union all
(SELECT email FROM 3table WHERE email = :email)');
答案 2 :(得分:1)
以前的答案都没有告诉您如何知道哪个表来自哪个表。因此,如果这是相关的,那么这是正确的UNION
$sql = "SELECT email, '1table' as fromTable FROM 1table WHERE email = :email";
$sql .= " UNION ALL";
$sql .= " SELECT email, '2table' FROM 2table WHERE email = :email";
$sql .= " UNION ALL";
$sql .= " SELECT email, '3table' FROM 3table WHERE email = :email";