我试图找出在我的表格中不同的clientId的总数
这是查询
$stmt = $conn->prepare("SELECT DISTINCT count(clientId) as totalrecords FROM quotes WHERE storeEmail = '". $store['email']. "'");
$stmt->execute();
$totalRecords = $stmt->fetch(PDO::FETCH_COLUMN);
echo 'Total Users Found with Request Quote : ' . $totalRecords . "<br /><br />";
echo 'Press Send button to send notifications to all users <br /><br />';
$query = "SELECT DISTINCT clientId FROM quotes WHERE storeEmail = '". $store['email']. "'";
$stmt = $conn->prepare($query);
$stmt->execute();
$clients = $stmt->fetchAll(PDO::FETCH_COLUMN);
第一个查询给出了147的总和,而第二个查询给了我60
第一次查询有什么问题。
答案 0 :(得分:1)
COUNT DISTINCT
是您正在寻找的:
$query = "SELECT COUNT(DISTINCT clientId) FROM quotes WHERE storeEmail = '". $store['email']. "'";
答案 1 :(得分:0)
SELECT DISTINCT count(clientId)
将返回您对clientId的计数,无论您是否使用DISTINCT。
但是第二个查询将返回不同的clietIds。
你应该使用
SELECT count(DISTINCT clientId)
答案 2 :(得分:0)
两件事:
DISTINCT进入了COUNT。 如果使用预准备语句,则应使用参数化查询,如:
$stmt = $conn->prepare("
SELECT count(DISTINCT clientId) as totalrecords FROM quotes WHERE storeEmail = ?");
$stmt->execute(array($store['email']));
$totalRecords = $stmt->fetch(PDO::FETCH_COLUMN);
echo 'Total Users Found with Request Quote : ' . $totalRecords . "<br /><br />";
echo 'Press Send button to send notifications to all users <br /><br />';
$query = "SELECT DISTINCT clientId FROM quotes WHERE storeEmail = ?";
$stmt = $conn->prepare($query);
$stmt->execute(array($store['email']));
$clients = $stmt->fetchAll(PDO::FETCH_COLUMN);