Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The current answer does work for the example that the OP has given, but it doesn't really answer the question. The OP asks for a query that orders by the most common characters, but the query only works if the DB entry contains a subset of the characters in the search query, and nothing more.</p> <p>For example, comparing <em>name111someignorechar</em> with <em>name1otherignorechar</em> wouldn't work.</p> <p>There's another solution, as explained here: <a href="http://tech-q-a.tumblr.com/post/58713827644/how-to-sort-results-based-on-the-number-of-identical" rel="nofollow">http://tech-q-a.tumblr.com/post/58713827644/how-to-sort-results-based-on-the-number-of-identical</a></p> <p>We can use a MySQL function that counts the number identical starting-characters for two strings:</p> <pre><code>DROP FUNCTION IF EXISTS countMatchingBeginChars; delimiter // CREATE FUNCTION `countMatchingBeginChars`( s1 text, s2 text ) RETURNS int(11) DETERMINISTIC BEGIN DECLARE s1_len, s2_len, min_len, j INT; SET s1_len = LENGTH(s1), s2_len = LENGTH(s2); IF s1_len &gt; s2_len THEN SET min_len = s2_len; ELSE SET min_len = s1_len; END IF; SET j = 0; WHILE j &lt;= min_len DO SET j = j + 1; IF SUBSTRING(s1,j,1) != SUBSTRING(s2,j,1) THEN RETURN j-1; END IF; END WHILE; RETURN min_len; END// delimiter ; </code></pre> <p>So,</p> <pre><code>SELECT countMatchingBeginChars("name111someignorechar", "name11") </code></pre> <p>would return 6 (as above), but so would </p> <pre><code>SELECT countMatchingBeginChars("name111someignorechar", "name11otherignore") </code></pre> <p>Now, we can sort the entries in the database according to the number of matching characters:</p> <pre><code>SELECT name FROM names ORDER BY countMatchingBeginChars("name111someignorechar",name) DESC, name </code></pre> <p>If only the entry with the most matching characters is required, we can just return only one result.</p> <pre><code>SELECT name FROM names ORDER BY countMatchingBeginChars("name111someignorechar",name) DESC, name LIMIT 1 </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload