title: Complex MySQL Query - Select Unique Records, Count, Insert and Delete
body: <p>I'm new! New here, new with MySQL and PHP. And I'm trying to do a little something which has got me all baffled up. Please try and help me guys.</p>
  
  <p>I have a table with some sample data as follows:</p>
  
  <pre>
  ID  NAME    ATTRIBUTE
  1   John     123
  2   Sean     654
  3   John     987
  4   Audrey   458
  5   John     123
  6   Audrey   589
  7   Peter    257
  8   Marc     125
  9   Audrey   326
  10  Stan     456
  11  Carol    698
  </pre>
  
  <p>And here's a list of what I intend to do - </p>
  
  <ol>
  <li><p>Select the first 6 records</p></li>
  <li><p>Find Unique Names from the 6 selected records – Expected Result : 3 Unique Names (John, Sean &amp; Audrey)</p></li>
  <li><p>Find the Number of Attributes for each Unique Name from the Selected 6 records – Expected Result: John (3 attributes) , Sean (1 attribute) and Audrey (2 attributes).</p></li>
  <li><p>Count the Number of identical attributes for each of the Unique name from the selected 6 records – Expected Result: Name=> John, Attribute=> 123, No. of Occurrence=> 2, Name=> John, Attribute=> 987, No. of Occurrence=> 1 etc.</p></li>
  <li><p>From the above selections, insert data to a new database table (e.g. Unique Names) in the format:</p>
  
  <p>a. NameID (Not the same one as the last table, new id – auto generated), 
     b. Name </p>
  
  <p>And in another table (e.g. Attributes) </p>
  
  <p>a. ID(Auto Generated),
     b. Attribute, 
     c. NameID (should be the same as ID in the last) – this is for the relationship between the Unique Names and Attributes table)
     d. Occurrence (of each attribute for each unique name)</p></li>
  <li><p>Once the new tables are filled with the data, I would like to Delete the top 6 selected record from the first table from where they are collected. (The Top Table)</p></li>
  </ol>
  
  <p>Can someone help me with the MySQL queries and supporting PHP codes for this one. Also, I would like to know the best and fastest possible way to query the MySQL for the above if I have millions of data in the tables.</p>