簡體   English   中英

具有相同數據的兩個單獨的SQL語句返回不同的結果

[英]Two separate SQL statements with the same data is returning different results

我要做的是將域列表發送到我的php腳本( $_POST['domains'] ),然后從域相似的表中獲取每個員工。

這是一個使用for循環執行多個查詢的示例。 這是標准的,但是需要更長的時間:

    $domains = explode(",", $_POST['domains']);
    $returnObj = new stdClass();
    $employees = [];
    foreach($domains as $domain) {
        $domainLike = "%".$domain;
        $query = $conn_databank->prepare("SELECT employee_id FROM employee WHERE domain LIKE ?");
        $query->bind_param('s', $domainLike);
        $query->execute();
        $result = $query->get_result();
        while($row = $result->fetch_assoc()) {
            array_push($employees, $row['employee_id']);
        }
    }
    $returnObj->employees = $employees;
    echo json_encode($returnObj);

現在,使用一組數據,我得到大約3900個結果,這是正確的。

我正在嘗試的另一種方法是使用LIKE ? OR LIKE ?創建動態的預處理語句LIKE ? OR LIKE ? LIKE ? OR LIKE ? 執行速度更快,但返回的結果卻不那么多(大約950):

    $queryString = "SELECT employee_id FROM employee";
    $actualQuery = "SELECT employee_id FROM employee";
    $bindVariables = [];
    for($i = 0; $i < count($domains); $i++) {
        $domainLike = "%".$domains[$i];
        if($i == 0) {
            $queryString .= " WHERE (domain LIKE ?";
            $actualQuery .= " WHERE (domain LIKE '".$domainLike."'";
        }
        else {
            $queryString .= " OR domain LIKE ?";
            $actualQuery .= " OR domain LIKE '".$domainLike."'";
        }
        if($i == count($domains) - 1) {
            $queryString .= ")";
            $actualQuery .= ")";
        }
        array_push($bindVariables, $domainLike);
    }

    $variables = count(explode("?", $queryString)) - 1;
    $bindings = [];
    $bindString = "";
    for($i = 0; $i < $variables; $i++)
        $bindString .= "s";
    array_push($bindings, $bindString);
    foreach($bindVariables as $variable)
        array_push($bindings, $variable);
    echo $actualQuery;
    $query = $conn_databank->prepare($queryString);
    call_user_func_array(array($query, 'bind_param'), makeValuesReferenced($bindings));
    $query->execute();
    $result = $query->get_result();
    $returnObj = new stdClass();

    $employees = [];
    while($row = $result->fetch_assoc()) {
        $employee = new stdClass();
        $employee->id = $row['employee_id'];
        array_push($employees, $employee);
    }
    $returnObj->employees = $employees;
    echo json_encode($returnObj);

忽略$actualQuery變量,那只是看它是否在正確構建查詢。

沒有示例,您的問題有點含糊。 但是,很明顯,一個域可以匹配多個like條件。 例如: xxx@gmail.com將同時匹配“ mail.com”和“ gmail.com”。

您沒有足夠的信息來判斷這是否是一個問題。 因此,一種想法是確保域完整 因此,使用“ @ gmail.com”而不是“ gmail”並使用email like concat('%', $domain)

這可能不起作用,因為您可能需要更多的靈活性(例如,匹配“ gmail.co.uk”)。 如果是這種情況,則OR可能更正確,因為它不包含重復項。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM