简体   繁体   中英

Sequential number field for each user in a common table

I have a user table and a goals table. Users can enter goals. Each table has an INT primary key that is auto incremented. Now I would like to add an INT field to the goals table that represents the users' goal ID such that if UserA enters 5 goals this new field will contain the values from 1 to 5. The same is true for UserB .. UserN. Can I do this on the MySQL side alone or do I have to pull the data out beforehand in my PHP code to determine the next number.

What about a query like this:

INSERT INTO goals(col1, col2, col3, user_goal_id) 
  SELECT :val1, :val2, :val3, MAX(user_goal_id)+1 
  FROM goals 
  WHERE user_id = :user_id 
  GROUP BY user_id

? I guess this is the easiest way...

Or maybe this could also work:

INSERT INTO goals(col1, col2, col3, user_goal_id) 
  SELECT :val1, :val2, :val3, user_goal_id+1 
  FROM goals 
  WHERE user_id = :user_id 
  ORDER BY user_goal_id DESC
  LIMIT 1

Or You can create a TRIGGER or some FUNCTION...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM