Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Unfortunately, MySQL does not have windowing functions which is what you will need. So you will have to use something like this:</p> <p><strong>Final Query</strong></p> <pre><code>select data, group_row_number, overall_row_num from ( select data, @num := if(@data = `data`, @num + 1, 1) as group_row_number, @data := `data` as dummy, overall_row_num from ( select data, @rn:=@rn+1 overall_row_num from yourtable, (SELECT @rn:=0) r ) x order by data, overall_row_num ) x order by overall_row_num </code></pre> <p>see <a href="http://sqlfiddle.com/#!2/bb591/33" rel="noreferrer">SQL Fiddle with Demo</a></p> <p><strong>Explanation:</strong></p> <p>First, inner select, this applies a mock <code>row_number</code> to all of the records in your table (See <a href="http://sqlfiddle.com/#!2/bb591/34" rel="noreferrer">SQL Fiddle with Demo</a>):</p> <pre><code>select data, @rn:=@rn+1 overall_row_num from yourtable, (SELECT @rn:=0) r </code></pre> <p>Second part of the query, compares each row in your table to the next one to see if it has the same value, if it doesn't then start the <code>group_row_number</code> over (see <a href="http://sqlfiddle.com/#!2/bb591/35" rel="noreferrer">SQL Fiddle with Demo</a>):</p> <pre><code>select data, @num := if(@data = `data`, @num + 1, 1) as group_row_number, @data := `data` as dummy, overall_row_num from ( select data, @rn:=@rn+1 overall_row_num from yourtable, (SELECT @rn:=0) r ) x order by data, overall_row_num </code></pre> <p>The last select, returns the values you want and places them back in the order you requested:</p> <pre><code>select data, group_row_number, overall_row_num from ( select data, @num := if(@data = `data`, @num + 1, 1) as group_row_number, @data := `data` as dummy, overall_row_num from ( select data, @rn:=@rn+1 overall_row_num from yourtable, (SELECT @rn:=0) r ) x order by data, overall_row_num ) x order by overall_row_num </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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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