php - 从不同表中选择数据,匹配并统计具有相同值的数字

标签 php mysql

编辑:我的数据库中有 2 个表:filesuser_logs。我想打印 files 中的所有值,并将它们与 user_logs 中的类似值进行匹配。

user_logsfiles 中的列相同:

  +++++++++++++++++++++
  + fileName | fileId +
  +++++++++++++++++++++

And I want the following output:

  +++++++++++++++++++++++++++++++++
  + fileName | no. of same values +
  +++++++++++++++++++++++++++++++++
  + fileNo1 |          3          +
  +++++++++++++++++++++++++++++++++
  + fileNo2 |          1          +
  +++++++++++++++++++++++++++++++++
  + fileNo3 |          0          +
  +++++++++++++++++++++++++++++++++

I don't understand what I researched. Here's my code:

$sql = "SELECT user_logs.fileName,count(*) as c FROM user_logs JOIN files ON user_logs.fileId = files.fileId UNION ALL SELECT files.fileName as file from files a group by a.fileId DESC ";
$result = mysqli_query($con,$sql);
while ($row = mysqli_fetch_assoc($result)) {
        $num_row = $row['c'];
    echo "<tr>";
        echo "<td>".$row['fileName']."</td>";
        echo "<td><a href='#' >".$num_row ." / 2 Schools Clicked</a></td>";      
    echo "</tr>";
    }

最佳答案

如果我理解你的意思,我想你想要这样的查询:

SELECT fileName, IF(t.cnt IS NULL, 0, t.cnt) AS c
FROM files LEFT JOIN
(SELECT count(*) AS cnt, fileId FROM user_logs GROUP BY fileId) AS t
ON files.fileId = t.fileId
ORDER BY fileName

关于php - 从不同表中选择数据,匹配并统计具有相同值的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43750313/

相关文章:

php - 如何在一列中插入多个选择框项目

php - 哪个更好 : require_once? 或 if (!defined ('FOOBAR' )) require?还是完全不同的东西?

php - 带有脚本标签的 tinyMCE 发布代码?

mysql - 计数频率还显示 "0"值

mysql - 寻找平均最高工资

php - 我应该使用两个脚本还是一个? `wordwrap()` 怎么样?

php - mysql 在短语中搜索关键字,按找到的最多关键字排序

java - Mysql连接器j错误

php - SQL - 为什么我的 INSERT 查询死了?

mysql - 如何查看DECIMAL字段的真实值?