[英]Count in mySQL based on a certain select
All, Say I have the following Select statement in mySQL: 全部,说我在mySQL中有以下Select语句:
$qry = "Select filename from upload where file_id='$file_id'";
$result = mysql_query($qry);
$resultset = mysql_fetch_array($result);
That query works fine but what I would also like to do is include a count of how many times that same filename appears somewhere else in that table in the same statement so I only have to run the mySQL statement once instead of getting that filename from this result and then executing another query like this one: 该查询工作正常,但我还想做的是包括相同文件名出现在同一语句中该表的其他位置的次数,因此我只需运行一次mySQL语句而不是从此获取该文件名结果,然后执行另一个像这样的查询:
$qrycheck = "Select COUNT(filename) from upload where filename='$resultset[filename]'";
Is there anyway to do this check in a single mySQL statement? 无论如何要在单个mySQL语句中执行此检查吗?
Thanks! 谢谢!
SELECT COUNT(filename) AS filenameOccurences, filename FROM upload WHERE filename = '$resultset[filename]' GROUP BY filename;
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'
Self-join is your friend. 自我加入是你的朋友。
$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'";
The DISTINCT
helps to prevent the same filename showing up multiple times (although if you're only grabbing the first row, it really doesn't matter). DISTINCT
有助于防止多次显示相同的文件名(尽管如果你只是抓住第一行,它确实没关系)。
If I understand correctly, you have several instances of 'filename' with different file_ids (I suppose that file_id is a unique ID, so it wouldn't make sense to count occurrences of file_id - you'd either get 1 or 0): 如果我理解正确,你有几个带有不同file_ids的'filename'实例(我想file_id是一个唯一的ID,所以计算file_id的出现次数是没有意义的 - 你得到1或0):
file_id filename
1 filename1.jpg
2 filename2.jpg
3 filename1.jpg
4 filename1.jpg
If that's the case, you have to JOIN upload with itself: 如果是这种情况,你必须自己加入上传:
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;
This will return the name in $resultset['filename'] and the number of instances in $resultset['instances']. 这将返回$ resultset ['filename']中的名称和$ resultset ['instances']中的实例数。
it could be help you 它可以帮到你
SELECT COUNT( * ) AS `Cnt` , `filename`
FROM `upload`
GROUP BY `filename`
limit 10;
and you wanna it maybe 而且你想要它
SELECT filename, count(*) as cnt
from upload
where file_id='###my_file_id###'
group by filename;
you can search with google 'mysql group by' 你可以用google'mysql group by'搜索
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.