I'm looking to use both DISTINCT and COUNT in a MySQL query, something like this:
SELECT DISTINCT `data1` AS new_data, COUNT(new_data) FROM table_name WHERE `data2`='$data2' AND `data3` = '$data3'
The goal being to loop through the DISTINCT results and do something with both the result itself, as well as the COUNT for that result.
Unfortunately, 开发者_高级运维I'm not too great with MySQL...
- I'm not sure if it can be done this way
- Is there any other approach that I could use to calculate this all directly in MySQL without multiple DB calls?
I assume you want to have a count
per data1
where rows match your conditions. Right?
Group by data1 and you're done:
SELECT `data1`, COUNT(*)
FROM table_name
WHERE `data2` = '$data2' AND `data3` = '$data3'
GROUP BY `data1`
I'm not sure to understand your question...
Do you want to do something like:
SELECT COUNT(DISTINCT `data1`) AS new_data FROM table_name
WHERE `data2`='$data2' AND `data3` = '$data3'
精彩评论