There is a simpler solution to this problem that you come across if you do not want to change the database structure by adding more tables.
In order not to change the structure of the database, I would suggest this simple solution.
Change the table of your icons and instead of using 0 or 1 as the value in the Column icons do this DATETIME field. When an icon is assigned to the user, write the date and time to the database as the value of the icon instead of 1 .
Thus, you can easily get the most recent icon for each user by completing a simple request. Therefore, to answer the following questions.
How can we bring a new badge or any badge according to the condition?
An example of SQL Fiddle , where the condition should contain in our query the last 7 days, icons for each user. The following are test data for the violin.
CREATE TABLE `TEST` ( `id` int(10) NOT NULL PRIMARY KEY, `name` varchar(255), `badge1` datetime, `badge2` datetime, `badge3` datetime, `badge4` datetime, `badge5` datetime ); INSERT INTO `TEST` (`id`,`name`,`badge1`,`badge2`,`badge3`,`badge4`,`badge5`) VALUES (1,'Nick','2016-12-10 13:58:13','0000-00-00 00:00:00','2016-12-07 17:28:19','0000-00-00 00:00:00','0000-00-00 00:00:00'), (2,'Sharah','2016-11-10 13:58:13','2016-11-17 13:01:13','2016-12-06 17:28:19','0000-00-00 00:00:00','0000-00-00 00:00:00'), (3,'John','2016-11-12 11:58:13','2016-11-19 13:05:13','2016-12-08 17:28:19','0000-00-00 00:00:00','0000-00-00 00:00:00') ;
Request for the last 7 days of icons using MySQL IF () and DATEDIFF ()
SELECT `id`,`name`, IF(DATEDIFF(NOW(),`badge1`)>7,'0000-00-00 00:00:00', `badge1`) as `Badge1`, IF(DATEDIFF(NOW(),`badge2`)>7,'0000-00-00 00:00:00', `badge2`) as `Badge2`, IF(DATEDIFF(NOW(),`badge3`)>7,'0000-00-00 00:00:00', `badge3`) as `Badge3`, IF(DATEDIFF(NOW(),`badge4`)>7,'0000-00-00 00:00:00', `badge4`) as `Badge4`, IF(DATEDIFF(NOW(),`badge5`)>7,'0000-00-00 00:00:00', `badge5`) as `Badge5` FROM `TEST`;
EDIT
You can also try this query to get the last icon (date and name), you can see the results in the updated SQL Fiddle
SELECT `id`,`name`,GREATEST(COALESCE(IF(DATEDIFF(NOW(),`badge1`)>0,CONCAT(`badge1`,'_badge1'),'0000-00-00 00:00:00')), COALESCE(IF(DATEDIFF(NOW(),`badge2`)>0,CONCAT(`badge2`,'_badge2'),'0000-00-00 00:00:00')), COALESCE(IF(DATEDIFF(NOW(),`badge3`)>0,CONCAT(`badge3`,'_badge3'),'0000-00-00 00:00:00')), COALESCE(IF(DATEDIFF(NOW(),`badge4`)>0,CONCAT(`badge4`,'_badge4'),'0000-00-00 00:00:00')), COALESCE(IF(DATEDIFF(NOW(),`badge5`)>0,CONCAT(`badge5`,'_badge5'),'0000-00-00 00:00:00'))) as `latest_badge` FROM `TEST`;
Conclusion of the above request. The last icon field for each user is a combination of the date name, time, and icon.
id name latest_badge 1 Nick 2016-12-10 13:58:13_badge1 2 Sharah 2016-12-06 17:28:19_badge3 3 John 2016-12-08 17:28:19_badge3