0

全部,假设我在 mySQL 中有以下 Select 语句:

$qry = "Select filename from upload where file_id='$file_id'";
$result = mysql_query($qry);
$resultset = mysql_fetch_array($result);

该查询工作正常,但我还想做的是计算同一文件名在同一语句中该表的其他位置出现的次数,因此我只需运行一次 mySQL 语句,而不是从中获取该文件名结果,然后执行另一个像这样的查询:

$qrycheck = "Select COUNT(filename) from upload where filename='$resultset[filename]'";

无论如何要在单个 mySQL 语句中执行此检查吗?

谢谢!

4

5 回答 5

2
SELECT COUNT(filename) AS filenameOccurences, filename FROM upload WHERE filename = '$resultset[filename]' GROUP BY filename;
于 2012-07-10T17:37:44.293 回答
0
SELECT u.filename, c.cnt
FROM upload AS u
INNER JOIN 
(
    SELECT COUNT(*) AS cnt, uu.filename 
    FROM upload AS uu
    GROUP BY uu.filename
) AS c ON u.filename = c.filename
WHERE u.file_id = '$file_id'
于 2012-07-10T17:43:38.037 回答
0

自加入是您的朋友。

$qry = "SELECT DISTINCT filename, a
    FROM (SELECT count(filename) AS a, file_id FROM upload GROUP BY file_id) AS x
    JOIN upload ON upload.file_id = x.file_id
    WHERE upload.file_id = '$file_id'";

DISTINCT有助于防止相同的文件名多次出现(尽管如果您只抓取第一行,那真的没关系)。

于 2012-07-10T17:43:58.347 回答
0

它可以帮助你

SELECT COUNT( * ) AS  `Cnt` ,  `filename` 
FROM  `upload` 
GROUP BY  `filename`
limit 10;

你可能想要它

SELECT filename, count(*) as cnt 
from upload 
where file_id='###my_file_id###' 
group by filename;

你可以用谷歌搜索'mysql group by'

于 2012-07-10T17:50:56.050 回答
0

如果我理解正确,您有几个具有不同 file_id 的 'filename' 实例(我认为 file_id 是一个唯一 ID,因此计算 file_id 的出现是没有意义的 - 你会得到 1 或 0):

  file_id  filename
  1        filename1.jpg
  2        filename2.jpg
  3        filename1.jpg
  4        filename1.jpg

如果是这种情况,您必须自己加入上传:

  SELECT uploads.filename, count(names.instance) AS instances FROM upload AS uploads
       JOIN upload AS names ON (uploads.filename = names.filename)
       WHERE uploads.file_id = '$file_id' GROUP BY uploads.filename;

这将返回 $resultset['filename'] 中的名称和 $resultset['instances'] 中的实例数。

于 2012-07-10T17:46:55.433 回答