J
J
Justlexa2015-04-11 12:26:08
MySQL
Justlexa, 2015-04-11 12:26:08

How to combine data in MySQL tables by non-unique features?

There are two tables in the MySQL database (5.5) of the following form: id (primary, int) - phone (varchar) - added (date) - userid (int
) correlate, in each of the tables id is unique only for it), in the second - only phone and added. It is necessary to transfer the data of the userid column from the first table to the second by matching phone-added pairs, but taking into account the fact that on the same day (the same value added) and for the same number (the same value phone) there may be different user_id .
Without the last condition, the query is simple:

UPDATE table2 AS t2
LEFT JOIN table1 AS t1 ON t2.phone = t1.phone AND t2.added = t1.added
SET t2.userid = t1.userid
WHERE t1.phone = t2.phone AND t1.added = t2.added

but accordingly, for several identical phone-added pairs, the first found userid is substituted.
For example:
table1: id - phone - added - userid
1001 - "8-800-000-00-01" - "2015-04-11" - 10
1002 - "8-800-000-00-01" - "2015 -04-11" - 12
1003 - "8-800-000-00-05" - "2015-04-11" - 15
1004 - "8-800-000-00-01" - "2015-04-11 " - 10
1005 - "8-800-000-00-02" - "2015-04-11" - 10
1006 - "8-800-000-00-01" - "2015-04-12" - 10

table2 : id - phone - added - userid
101 - "8-800-000-00-01" - "2015-04-11" - XX
102 - "8-800-000-00-05" - "2015-04- eleven"
- XX 108 - "8-800-000-00-02" - "2015-04-14" - XX Please tell me how this can be implemented? It is acceptable to use SQL (including stored procedures) and php5.


PS: I don't ask for a ready request/script

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vladimir Boliev, 2015-04-11
@voff

Well ... as an option, you can add an exported field to the table2 table, which indicates that this row has already been transferred.
The algorithm is as follows:
We look for a row in table2 with the desired phone, the desired date and exported=0
If we find it, we transfer the user_id and set exported=1
If we don’t find it, we transfer the user_id from any line that has a suitable phone and date and set exported=1

A
Alexander, 2015-04-13
@wiggle

Maybe it's worth normalizing the database structure and moving phone and added into a separate entity common to 2 tables?

A
Artyom Karetnikov, 2015-04-11
@art_karetnikov

Well, there is nothing special to think about, if I understood your request correctly.
select min(User_id) from your table group by Phone, Added -- this will get the first value inserted by this phone and date.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question