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
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
Share on other sites

once the site grows, there's a possibility of lots of dupes..

could there be a way of just combining an update, insert, and just select

statements? i think there's a huge overhead in creating a new table

and copying all those rows..

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.