Jump to content

help with query


mark_nsx

Recommended Posts

Hi all,

 

Say i have a table called `users_events` with fields `user_id` and `event_id` with

the following data:

user_id  |  event_id
-------------------
1          |      1
1          |      3
2          |      1
2          |      2
2          |      3
-------------------

 

What I'd like to do is merge rows with user_id = 2 into user_id = 1 and delete duplicate ones (event_id), which will

return the result:

 

user_id  |  event_id
-------------------
1          |      1
1          |      3
1          |      2
-------------------

 

Thanks in advance for the help! Cheers!

Link to comment
https://forums.phpfreaks.com/topic/106279-help-with-query/
Share on other sites

First you'll need to make all your user_id that are 2 into 1:

 

UPDATE users_events SET user_id=1 WHERE user_id=2

 

Because there is no 'function' in mysql to remove duplicates, here is the simplest way to achieve it:

 

CREATE TABLE new_users_events(
  user_id INT NOT NULL AUTO_INCREMENT,
  PRIMARY KEY(id),
  event_id INT)

INSERT INTO new_users_events(user_id, event_id)
   SELECT DISTINCT user_id, event_id FROM users_events;

DROP TABLE users_events;

RENAME TABLE new_users_events users_events;

 

I can't test this from where I am, but I think this will work.

Link to comment
https://forums.phpfreaks.com/topic/106279-help-with-query/#findComment-544680
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.