简体   繁体   English

在PDO查询中使用COUNT和内部联接

[英]Using COUNT and inner join in PDO query

What would be the best way of writing this SQL statement as a PDO query? 将此SQL语句编写为PDO查询的最佳方法是什么? I want it to return the number of queries as a number. 我希望它以数字形式返回查询数。

SELECT  COUNT(*) totalCount
FROM    ts_room a
        INNER JOIN ts_roompref b
            ON a.id = b.room_ID
        INNER JOIN ts_request c
            ON b.request_ID = c.roompref_ID
WHERE   c.day_ID = 1 AND c.period_ID = 1

This is what I was thinking: 这就是我的想法:

$room_ID = $_POST["room"];

$sql = "SELECT  COUNT(*) totalCount
FROM    ts_room a
        INNER JOIN ts_roompref b
            ON a.id = b.:room_ID
        INNER JOIN ts_request c
            ON b.request_ID = c.roompref_ID
WHERE   c.day_ID = 1 AND c.period_ID = 1";

$stm = $pdo->prepare( $sql );
$stm->execute( array( ':room_ID' => $room_ID) );
$rows = $stm->fetchAll();

// echo row count here
$count = $stm->rowCount();

If you want to get the total number of rows, use fetchColumn function. 如果要获取总行数,请使用fetchColumn函数。

And one more correction, since you are using JOIN here so in the ON clause , you can't use the variable value, use column name only. 还有一项更正,因为您在这里使用JOIN ,所以在ON子句中 ,您不能使用变量值,而只能使用列名。

$room_ID = $_POST["room"];

$sql = "SELECT  COUNT(*) totalCount
FROM    ts_room a
        INNER JOIN ts_roompref b
            ON a.id = b.room_ID
        INNER JOIN ts_request c
            ON b.request_ID = c.roompref_ID
WHERE   c.day_ID = 1 AND c.period_ID = 1 and b.room_ID=:room_ID";

$stm = $pdo->prepare( $sql );
$stm->execute( array( ':room_ID' => $room_ID) );
$rows = $stm->fetchColumn();

Please check your query once:I have highlited the condition ehich you doing wrong this will be put in where clause . 请检查一下您的查询:我已将条件高亮显示为您做错了,这将放在where子句中。

  SELECT  COUNT(*) totalCount
    FROM    ts_room a
            INNER JOIN ts_roompref b
                 // ON a.id = b.:room_ID
            INNER JOIN ts_request c
                ON b.request_ID = c.roompref_ID
    WHERE   c.day_ID = 1 AND c.period_ID = 1

I guess your code will be look like this: 我想您的代码将如下所示:

$room_ID = $_POST["room"]; $ room_ID = $ _POST [“房间”];

$sql = "SELECT  COUNT(*) totalCount
FROM    ts_room a
        INNER JOIN ts_roompref b
            ON a.id = b.room_ID
        INNER JOIN ts_request c
            ON b.request_ID = c.roompref_ID
WHERE   c.day_ID = 1 AND c.period_ID = 1 and b.room_ID=:room_ID";

$stm = $pdo->prepare( $sql );
$stm->execute( array( ':room_ID' => $room_ID) );
$rows = $stm->fetchAll();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM