使用JOIN从数据库中检索结果

时间:2013-07-28 16:17:51

标签: php mysql join

我尝试将函数的操作次数减少到只有一个查询,但现在我无法检索任何结果:

function retrive_avaible_operator($Hostname, $Username, $Password, $DatabaseName, $SupportUserPerDepaTable, $SupportUserTable,$dep){
    $query = "SELECT b.id  
              FROM ".$SupportUserTable." b
              INNER JOIN ".$SupportUserPerDepaTable." a
                  ON b.id=a.user_id
              WHERE a.department_id=? AND b.holiday='0' AND a.user_id!=".$_SESSION['id']." 
              ORDER BY b.assigned_tickets ASC LIMIT 1";

    $mysqli = new mysqli($Hostname, $Username, $Password, $DatabaseName);
    $stmt = $mysqli->stmt_init();
    $prepared = $stmt->prepare($query);

    if($prepared){
        if($stmt->bind_param('i', $dep)){
            if($stmt->execute()){
                $stmt->store_result();
                $result = $stmt->bind_result($camaro);
                if($stmt->num_rows>0){
                    while (mysqli_stmt_fetch($stmt))
                        $selopid=$camaro;
                    return $selopid;
                }
                else
                    return 'No Operator Available';
            }
            else
                return mysqli_stmt_error($stmt);
        }
        else
            return mysqli_stmt_error($stmt);
    }
    else
        return mysqli_stmt_error($stmt);
}

在此之前尝试操作(这是两个不同的查询):

  1. $SupportUserPerDepaTable a.department_id=?
  2. 中选择所有ID
  3. $SupportUserTable中选择所有ID,其中id位于之前的结果中,holiday='0'
  4. 虽然有效,但现在只返回No Operator Available

    这些是表格:

    CREATE TABLE IF NOT EXISTS `razorphyn_support_user_departments` (
    `id`                BIGINT(11)  UNSIGNED    NOT NULL    AUTO_INCREMENT,
    `department_id`     BIGINT(11)  UNSIGNED    NOT NULL,
    `department_name`   VARCHAR(70)             NOT NULL,
    `user_id`           BIGINT(11)  UNSIGNED    NOT NULL,
    `holiday`           ENUM('0','1')           NOT NULL    DEFAULT '0',
    PRIMARY KEY (`id`),
    UNIQUE KEY(`department_name`,`user_id`),
    INDEX(`department_id`,`department_name`,`user_id`)
    ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=0;
    

    CREATE TABLE IF NOT EXISTS `razorphyn_support_users` (
    `id`                BIGINT(15)      UNSIGNED        NOT NULL AUTO_INCREMENT,
    `name`              VARCHAR(50)                     NOT NULL,
    `mail`              VARCHAR(50)                     NOT NULL,
    `password`          VARCHAR(200)                    NOT NULL,
    `reg_key`           VARCHAR(260)                    ,
    `tmp_password`      VARCHAR(87)                     ,
    `ip_address`        VARCHAR(50)                     NOT NULL,
    `status`            ENUM('0','1','2','3','4')       NOT NULL    DEFAULT '3',
    `holiday`           ENUM('0','1')                   NOT NULL    DEFAULT '0',
    `mail_alert`        ENUM('no','yes')                NOT NULL    DEFAULT 'yes',
    `assigned_tickets`  INT(5)          UNSIGNED        NOT NULL    DEFAULT 0,
    `solved_tickets`    BIGINT(11)      UNSIGNED        NOT NULL    DEFAULT 0,
    `number_rating`     BIGINT(6)       UNSIGNED        NOT NULL    DEFAULT 0,
    `rating`            DECIMAL(4,2)    UNSIGNED        NOT NULL    DEFAULT 0,
    PRIMARY KEY (`id`),
    UNIQUE KEY(`mail`),
    INDEX (`name`,`mail`,`status`,`holiday`,`assigned_tickets`,`solved_tickets`)
    ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=55;
    

    修改
    我发现(不幸的是,因为前面的代码非常丑陋和混乱)(我删除了所有控件,但是它有效):

    function retrive_avaible_operator($Hostname, $Username, $Password, $DatabaseName, $SupportUserPerDepaTable, $SupportUserTable,$dep){
    
    $query = "SELECT `user_id`  FROM ".$SupportUserPerDepaTable." WHERE `department_id`=? AND `user_id`!=".$_SESSION['id'] ;
    $mysqli = new mysqli($Hostname, $Username, $Password, $DatabaseName);
    $stmt = $mysqli->stmt_init();
    $prepared = $stmt->prepare($query);
        $stmt->bind_param('i', $dep)
            $stmt->execute()
                $stmt->store_result();
                $operator=array();
                $result = $stmt->bind_result($camaro);
                if($stmt->num_rows>0){
                    while (mysqli_stmt_fetch($stmt))
                        $operator[]=$camaro;
                    $operator=join(',',$operator);
                    $query = "SELECT `id`  FROM ".$SupportUserTable." WHERE `id` IN (".$operator.") AND `holiday`='0' ORDER BY `assigned_tickets` ASC LIMIT 1" ;
                    $prepared = $stmt->prepare($query);
                    $prepared)
                        $stmt->execute()
                            $stmt->store_result();
                            $result = $stmt->bind_result($camaro);
                            if($stmt->num_rows>0){
                                while (mysqli_stmt_fetch($stmt))
                                    $selopid=$camaro;
                                return $selopid;
                            }
                            else{
                                $query = "SELECT `id` FROM ".$SupportUserTable." WHERE `status`=2 AND `holiday`=0 AND `id`!=".$_SESSION['id']." ORDER BY `assigned_tickets` ASC, `solved_tickets` ASC LIMIT 1" ;
                                $prepared = $stmt->prepare($query);
                                $prepared
                                    $stmt->execute()
                                        $stmt->store_result();
                                        $result = $stmt->bind_result($camaro);
                                        if($stmt->num_rows>0){
                                            while (mysqli_stmt_fetch($stmt))
                                                $selopid=$camaro;
                                            return $selopid;
                                        }
                                        else
                                            return 'No Operator Available';
                            }
                }
                else{
                    $query = "SELECT `id` FROM ".$SupportUserTable." WHERE `status`='2' AND `holiday`='0' AND `id`!=".$_SESSION['id']." ORDER BY `assigned_tickets` ASC, `solved_tickets` ASC LIMIT 1" ;
                    $prepared = $stmt->prepare($query);
                        $stmt->execute()
                            $stmt->store_result();
                            $result = $stmt->bind_result($camaro);
                            if($stmt->num_rows>0){
                                while (mysqli_stmt_fetch($stmt))
                                    $selopid=$camaro;
                                return $selopid;
                            }
                            else
                                return 'No Operator Available';
                }
    $mysqli->close();
    }
    

1 个答案:

答案 0 :(得分:0)

你应该能够大大缩小这一点。在开始时,您只是查询$SupportUserPerDepaTable获取user_id,只是将它们加入到第二个查询的逗号分隔字符串中。您应该能够通过将其转换为子查询来消除此问题。第3和第4个查询是多余的,是前一个if / else情况的产物,因此您可以将这些查询组合起来,因为我们已经消除了top if条件。使用底部的“丑陋”代码,我将其浓缩为:

$mysqli = new mysqli($Hostname, $Username, $Password, $DatabaseName);
$stmt = $mysqli->stmt_init();
$query = "
SELECT      `id`  
FROM        ".$SupportUserTable." 
WHERE       `id` IN (
    SELECT      `user_id`  
    FROM        ".$SupportUserPerDepaTable." 
    WHERE       `department_id`= ? 
    AND         `user_id`!=".$_SESSION['id']."
)
AND         `holiday`='0'
ORDER BY    `assigned_tickets` ASC 
LIMIT       1" ;

$prepared = $stmt->prepare($query);
$stmt->bind_param('i', $dep);
$stmt->execute();
$stmt->store_result();
$operator=array();
$result = $stmt->bind_result($camaro);
if($stmt->num_rows>0){
    while (mysqli_stmt_fetch($stmt))
        $selopid=$camaro;
    return $selopid;
}
else{
    $query = "
    SELECT      `id` 
    FROM        ".$SupportUserTable." 
    WHERE       `status`= 2 
    AND         `holiday`=0 
    AND         `id`!=".$_SESSION['id']." 
    ORDER BY    `assigned_tickets` ASC
                ,`solved_tickets`  ASC 
    LIMIT       1" ;
    $prepared = $stmt->prepare($query);
    $stmt->execute();
    $stmt->store_result();
    $result = $stmt->bind_result($camaro);
    if($stmt->num_rows>0){
        while (mysqli_stmt_fetch($stmt))
            $selopid=$camaro;
        return $selopid;
    }
    else{
        return 'No Operator Available';
    }
}
$mysqli->close();

您可以通过使用组合限制为1的UNION进一步将2个查询压缩为1:

(
    SELECT      `id`  
    FROM        ".$SupportUserTable." 
    WHERE       `id` IN (
        SELECT      `user_id`  
        FROM        ".$SupportUserPerDepaTable." 
        WHERE       `department_id`= ? 
        AND         `user_id`!=".$_SESSION['id']."
    )
    AND         `holiday`='0'
    ORDER BY    `assigned_tickets` ASC 
    UNION
    SELECT      `id` 
        FROM        ".$SupportUserTable." 
        WHERE       `status`= 2 
        AND         `holiday`=0 
        AND         `id`!=".$_SESSION['id']." 
        ORDER BY    `assigned_tickets` ASC
                    ,`solved_tickets`  ASC 
)
LIMIT       1;

或可能使用OR条件,具体取决于dept表中员工的状态代码,如:

SELECT      `id`  
FROM        ".$SupportUserTable." 
WHERE       `holiday`='0'
AND (       
        `id`    IN (
            SELECT      `user_id`  
            FROM        ".$SupportUserPerDepaTable." 
            WHERE       `department_id`= ? 
            AND         `user_id`!=".$_SESSION['id']."
        )
        AND     `status`= ('some code other than 2?') 
    )
    OR  (
                `status`= 2 
        AND     `id`! = ".$_SESSION['id']."
)
ORDER BY    status (asc or desc?)
            ,`assigned_tickets` ASC
            ,`solved_tickets`  ASC 
LIMIT       1;

我没有对此进行测试,因为这需要花费太多时间来设置数据库表,输入样本数据并全部测试,所以如果有任何小错误,请原谅我,但这应该指向正确的方向。如果这不起作用并且您想要将一些示例数据发布到http://sqlfiddle.com/并提供一些预期输出的示例,我将重试一些查询以查看我能做什么。