获取用户

时间:2018-03-25 17:45:52

标签: mysql sql

您好我有一个名为用户的表格和 user_details 我的 user_details 表格存在问题。

用户表

usr_id |命名
1 |约翰
2 |玛丽
3 |雅各布

user_details表

det_id | usr_id |看出
1 | 1 | 0
2 | 2 | 1
3 | 3 | 0
3 | 3 | 0

这是我的SQL查询

$sql = "SELECT *, COUNT(seen) 
    FROM user_details 
    GROUP BY usr_id 
    HAVING COUNT(seen)=0"; 

$sqlUnseen = mysqli_query($DB, $sql);

$result = mysqli_num_rows ($sqlUnseen);

echo $result;

我想获取记录用户在表格中看不见的(0)的数量 例如,我以用户 3 身份登录,那么输出应 2 ,因为 user_details 表中的用户 3 2 零。

谢谢大家。

*我的输出是1 1

2 个答案:

答案 0 :(得分:0)

这是应该有效的SQL语句。此外,在您的代码中,您只显示返回的行数,这不是您想要的。您需要count(*)列的值。这还会在表中显示查询中的结果行:

$sql = "SELECT a.*, 
    COUNT(seen) as cnt
    FROM users a
    JOIN user_details b
        ON a.usr_id = b.usr_id
    WHERE a.usr_id = 3
    GROUP BY a.usr_id 
    HAVING cnt = 0"; 

$sqlUnseen = mysqli_query($DB, $sql);
$allrows = mysqli_fetch_all($sqlUnseen,MYSQLI_ASSOC);
$numrows = mysqli_num_rows ($sqlUnseen);

echo "<p>Number of rows returned: ".$numrows."</p>\n";
if($allrows) {
    echo "<table>\n";
    echo "<tr>\n";
    foreach($allrows[0] as $colname => $colval) {
        echo "<td>".$colname."</td>\n";
    }
    echo "</tr>\n";
    foreach($allrows as $recno => $row) {
        echo "<tr>\n";
        foreach($row as $colname => $colval) {
            echo "<td>".$colval."</td>\n";
        }
        echo "</tr>\n";
    }
    echo "</table>\n";
}

答案 1 :(得分:0)

SELECT *, COUNT(seen) AS NumberOfUnseens FROM users us
INNER JOIN user_details ud
ON us.usr_id=ud.usr_id
WHERE ud.seen=0 AND ud.usr_id=3
GROUP BY ud.usr_id

没有加入

SELECT *, COUNT(seen) AS NumberOfUnseens FROM user_details 
WHERE seen=0 AND usr_id=3 GROUP BY usr_id;

现场演示

  

http://sqlfiddle.com/#!9/bc3f08/14