I have a mysql database, I want to select all values that are equal on “name” and “postcode”. And the query needs to select the most common data in the other fields.
If I have:
name postcode test test2
a a 1 2
a a 1 2
a a 2 1
a a 1 1
a a 1 1
Then this needs to return
a a 1 1
Because (test)1 is 4 times in the table, and (test2)1 is there 3 times. So I need the most common data in the Column where the name and the postcode is the same.
This is my first approach:
If you don’t need high performance this is a solution. If this query is often performed then you should look for another approach.
EDITED
If you need more performance and also you need distinct rows, you can remove
distinctand appendgroup by name, postcodeclause at the end of the query.Query looks like:
This is not standard SQL but mysql allow this for better performance:
Quoting MySQL doc: