0

I need to get the most registered name from a database, based on count().

I have a table in the database that has these columns and data

id    |    name    |    code
1          Craig        4567
2          John         4567
3          Liam         4568
4          sam          4569
5          sam          4569

and what I need to do is count the name field so that which ever name appears most will be displayed. In this case its Sam.

I have tried:

$ck_af = $wpdb->get_results( 
             $wpdb->prepare("SELECT * FROM wp_code_log ORDER BY CONVERT(COUNT(name), UNSIGNED INTEGER) DESC LIMIT 1")
         );

can anyone see what is happening?

It is ouputting Craig.

I need it to output which ever name is most stored and also the code afterwards, so it should be:

sam : 4569
1
  • 1
    select name, code from my_table group by name, code order by count(*) desc limit 1 Commented Aug 11, 2014 at 9:09

2 Answers 2

1

You need to select the name and then order them by the name. This will make all instances that are the same appear as one result. Then you order by counting how many of the results there are. like so:

global $wpdb;
$ck_af = $wpdb->get_results( $wpdb->prepare("SELECT name FROM wp_code_log GROUP BY name ORDER BY count(*) DESC LIMIT 1"));
Sign up to request clarification or add additional context in comments.

2 Comments

Worked great. Do you know if this is SQL Injection free?
Alos, How can I get the amount to be outputted so that it will tell me how many times it was in the database
0

I think that the COUNT(name) will count all the names in the database. So for every record it gives 5. You will have to define a condition for the names to be counted:

SELECT * FROM wp_code_log AS t1
ORDER BY CONVERT(SELECT COUNT(name) FROM wp_code_log AS t2 WHERE t2.name = t1.name, UNSIGNED INTEGER) DESC LIMIT ONE

Comments

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.