0

In mySql, Is it possible to do an insert based on something? In my case, I'd like to do an insert depending on the users location. Those locations are like US, UK, AU, CA etc. So if the location is US i'd like to do 1-0001, 1-0002 etc, for uk 2-001, 2-002 etc.

Maybe by using case of something like that this could be possible?

My current insert goes like this:

insert into prodClassifieds (userId, userName, classStatus, classCountry, classId)
   select
     $userId, 
     '$userName', 
     1,
     '$userCountry',
     IFNULL((MAX(classId)+1) ,0)
   FROM prodClassifieds

EDIT: I can leave out the - in 1-0001. Also the MAX(col) is MAX(classId) not the one I originally posted. The next value is 1 + the current value that's there.

Norman
  • 6,159
  • 23
  • 88
  • 141

2 Answers2

0

Yes this is possible,

insert into prodClassifieds 
(userId, userName, classStatus, classCountry, classId) 
select $userId, '$userName', 1,
'$userCountry', 
 case when userCountry='US' then 
MAX(sc_stack_id)+1 else 0 end
FROM prodClassifieds 

U can add several conditions as per your need

Mariappan Subramanian
  • 9,527
  • 8
  • 32
  • 33
0

Use CASE WHEN as follows:

insert into prodClassifieds (userId, userName, classStatus, classCountry, classId)
   select
     $userId, 
     '$userName', 
     CASE '$userCountry' WHEN 'US' THEN 10000 WHEN 'UK' THEN 20000 ELSE 90000 END CASE
     + 1,
     '$userCountry',
     IFNULL((MAX(sc_stack_id)+1) ,0)
   FROM prodClassifieds 
Atheer Mostafa
  • 735
  • 3
  • 8