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

时间:2017-05-03 02:56:39

标签: php mysql

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

user_logsfiles中的列相同:

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

我想要以下输出:

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

我不明白我研究的内容。这是我的代码:

$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>";
    }

1 个答案:

答案 0 :(得分:0)

如果我理解你,我认为你想要这样的东西作为你的查询:

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