Mysql – Table attribute for sorting

database-designMySQL

I have 3 Tables, a User table, a Tracks table and a Likes table. Users can like as many tracks as they want and one track can be liked by multiple users. In my Likes table I have two foreign keys to the User and to the Tracks table.

I'm getting the data from an API, that sends it in the correct order, latest likes sent first. But there's no field like a date when it was liked on. It's only the order. Now I want to put the likes in my database in the correct order, so I made a third column in my Likes table that is named liked_order. It's an AUTO_INCREMENTED value, therefore my foreign keys and the liked_order attribute are my primary keys for this table. Unfortunately it is now possible for a user to like a track twice. If the AUTO_INCREMENT value wouldn't have to be a primary key everything would be fine.

I've ran out of ideas…

EDIT: I have to use MySQL

Best Answer

Without seeing the table schema, I see two options:

  1. Adjust the schema so that the Foreign Keys(FK) are not part of the Primary Key(PK); only the AUTO_INCREMENT column is the PK. The Foreign Keys can still be Unique Indexes to prevent multiple likes of a particular track by the same user. This won't work of course if the FKs are part of a partitioning scheme.
  2. Take out the AUTO_INCREMENT column and add a TIMESTAMP(0) DEFAULT CURRENT_TIME column. The timestamp column will take up as much space as an INT AUTO_INCREMENT column. The downside to this is all rows before adding the timestamp column would not have an order.