0

我已经从我的代码中提取了这个片段,因为我担心有更好的方法来做到这一点。我希望有人可以帮助我或为我指明正确的方向。

基本上这段代码检查数据库中的许多表并检查结果是否返回。

    $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){

有没有更好的办法?或更有效的方式,它可以告诉我结果是在哪个表中找到的?

4

3 回答 3

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"; 
于 2013-04-16T17:56:13.717 回答
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)'); 
于 2013-04-16T17:42:20.770 回答
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);
于 2013-04-16T17:40:54.667 回答