Question

My users are splited in user tables over 5 databases. Looks like this:

db1.user
id  token  app  lang  last_update
XX  1      a    en    11:00
XX  2      a    en    12:00


db2.user
id  token  app  lang  last_update
XX  1      b    en    12:00
XX  2      a    en    16:00

db3.user
…

Now i need all users in one view, it should look like this (token and app are together the primary key):

view db.user_all
id  token  app  lang  last_update
XX  1      a    en    11:00
XX  1      b    en    12:00
XX  2      a    en    16:00

I tried to union everything:

create view `db`.`user_all` AS 
SELECT * FROM `db1`.`user` union 
SELECT * FROM `db2`.`user`

The result looks like this:

view db.user_all
id  token  app  lang  last_update
XX  1      a    en    11:00
XX  2      a    en    12:00
XX  1      b    en    12:00
XX  2      a    en    16:00

My sql statement deletes the duplicated rows, but if the last_update is different i got a duplicated user in the result view. How to solve this? I need all data, also the newest last_update.

Was it helpful?

Solution

Try this:

CREATE VIEW user_intermediate AS
SELECT * FROM db1 UNION ALL SELECT * FROM db2
ORDER BY last_update DESC
;

CREATE VIEW user_all AS
SELECT *
FROM user_intermediate
GROUP BY app, token
;

Assuming App and Token make the user key, the user_all view should have the distinct users with the latest last_update across both tables.

OTHER TIPS

Try using a DISTINCT along with a MAX, so something like this:

SELECT DISTINCT id,  token,  app,  lang,  max(last_update) FROM (
    SELECT * FROM `db1`.`user` union 
    SELECT * FROM `db2`.`user`
)
GROUP BY id, token, app, lang

you may need to use an alias after the last bracket.


update

Apparently, MYSQL cannot have subqueries in views so you'll have to create this as a stored procedure instead http://dev.mysql.com/doc/refman/5.0/en/create-procedure.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top