0

i want to count multiple values from 3 columns and sorted descending using PHP mysqli, and I can't do it.

name1 name2 name3
mike jack rose
jack mike Mary
jack Mary John

expect output:

jack 3 
mike 2
mary 2
rose 1
John 1

My code:

$query = "select count(*) as c from work" ;
$result = $con->query($query);
$count = $result->fetch_object()->c;

1 Answer 1

1

Use UNION to get them all into a single column. Then use COUNT(*) and GROUP BY:

$query = "
SELECT name, COUNT(*) AS c
FROM (
    SELECT name1 AS name
    FROM work
    UNION ALL
    SELECT name2 AS name
    FROM work
    UNION ALL
    SELECT name3 AS name
    FROM work
) AS x
GROUP BY name
ORDER BY c DESC";
$result = $con->query($query);
while ($row = $result->fetch_object()) {
    echo "$row->name $row->c<br>";
}
Sign up to request clarification or add additional context in comments.

3 Comments

could you write the fetch code cause it doesn't work for me
I added the fetch loop.
finally, thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.