Assume I have the following tables:
tableA
a_name | age | country
Jordan | 5 | Germany
Jordan | 6 | Spain
Molly | 6 | Spain
Paris | 7 | France
John | 7 | Saudi Arabia
John | 5 | Saudi Arabia
John | 6 | Spain
tableB
id (auto increment primary key)
| age | country | group_num (initially null)
1 | 5 | Germany |
2 | 6 | Spain |
3 | 7 | France |
4 | 7 | Spain |
5 | 8 | France |
6 | 9 | France |
7 | 2 | Mexico |
8 | 7 | Saudi Arabia |
9 | 5 | Saudi Arabia |
I want to be able to do some kind of select/update where I am able to get the following values for the "group_num" column:
tableB
id (auto increment primary key)
| age | country | group_num
1 | 5 | Germany | 1
2 | 6 | Spain | 1
3 | 7 | France | 1
4 | 7 | Spain |
5 | 7 | France | 2
6 | 9 | France |
7 | 2 | Mexico |
8 | 7 | Saudi Arabia | 1
9 | 5 | Saudi Arabia | 1
group_num is assigned based on the criteria of:
1) Places person "a_name" went.
2) Whether other people visited that same country. (regardless of age).
The reason why id's 1,2,3,8,9 all have the same groupId is because Jordan, Molly, and Paris all happen to be somehow linked because of the above two criteria. (they all went to spain) and other countries, i.e. Germany was visited by Jordan who also visited spain, so it has the same group_num. Saudi Arabia was visited by John, who also visited spain, so it has the same group_num.
is there some SQL query or queries (may or may not involve creation of other "complementary" tables to get to the desired result shown above? (i.e. it is okay if group_num should first to be filled with auto_incrementing values like the "id", then updated later if it is necessary. (it is okay to have non-null values for the other value fields currently shown as "(empty)"
Cursors/iteration is very slow... The following are the steps I would perform to fill out those values, very slow process using cursors, if I can get rid of this it would be great:
You will need an iterative approach which will be based on each new item added to Table1, if you execute the following statements for each such item it will be fast and efficient:
Here is SQLFiddle for state of the db just before inserting the last record in Table 1.
BTW: Your example is not entirely consistent with your description , i assume you signed France 7 as group 1 by mistake, since Paris has no relation to no one in group 1.
Notice the selects that i'm executing:
After finding out that you have two disjoint sets that becomes joined as a result of newly inserted record , you may that UPDATE all the group num previously assigned as the second group number to the first one, in such way:
UPDATE Table2 set group_num = 1 where group_num = 3
So i have not used any cursors , but this update is per insert for Table 1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With