MYSQL string list of items into columns deleting some pushing in coding
I am new to MYSQL and have a problem. Its related to php too I guess.
I have a table, ID,CODE,string1,string2,string3,string4,string5,string6,string7
now, each customer has a unique code. Each code can store a maximum of 7 strings in their "list".
PROBLEM - if the customer adds a new item or items (important!) to their list and their list is already full, then the list should push out the oldest string and add the new strings to the end.So say, string 1 to 7 are filled with text t1 to t7. then customer wants to add new items t8 and t9, I need to delete t1 and t2, move everything down 2 spaces and add t8 where t6 was and t9开发者_JS百科 where t7 was (at the beginning). This is easy to do in java or normal programming, but how can I do this quickly and easily and efficiently in mysql/php code?
Is it possible? Is this the correct way to do things in mysql? Is there a better way? sorry
I think your problem is more related to your database schema. You could change (if you can) your db like this :
User(id, code)
List(id, user_id, date, value)
Then, for your user (1, 'xxx'), you add 7 values :
INSERT INTO List (user_id, `date`, `value`) VALUES
(1, NOW(), 1),
(1, NOW(), 2),
(1, NOW(), 3),
(1, NOW(), 4),
(1, NOW(), 5),
(1, NOW(), 6),
(1, NOW(), 7);
And, following your description, if you add two new numbers (8, 9) :
DELETE FROM List ORDER BY `date` DESC, id DESC LIMIT 2; // 2 is the quantity you'll add
and then add the two new entries :
INSERT INTO List (user_id, `date`, `value`) VALUES
(1, NOW(), 8),
(1, NOW(), 9);
Now, suppose you have three customer :
User(1, 'xxx') // customer n°1
User(2, 'yyy') // customer n°2
User(3, 'zzz') // customer n°3
The difference would occur in the user_id column in the List table : (I reduce to 2 entry per user) :
INSERT INTO List (user_id, `date`, `value`) VALUES
(1, NOW(), 1),
(1, NOW(), 2),
(2, NOW(), 1), // look! I change the user_id
(2, NOW(), 2),
(3, NOW(), 1), // look! I change the user_id here too
(3, NOW(), 2);
Now suppose you want to have the list of the user 3, you do this request :
SELECT value FROM List WHERE user_id = 3; // the id of the user you want to have his list
This will return two rows : 1, 2
You don't have to create a table per user, you just have to add an extra column to identify which user belongs the data in the same table than others users.
Hope this helps ! :)
Its not exactly normal form, or good form in any way. But to accomplish this you could just use a serialized array from PHP, stored in a single field. Then push and pop in php as needed.
精彩评论