My application has different levels of users, Admin users and Organization users.
Admin users are stored in broker database and since each organization is a different database, organization users are stored in their own databases. I have a table in the organization databases that I want to use the users Id in the broker user table, in each organization databases as a foreign key. How can I create the relation between these two tables even tho they are in different dbs?
As mentioned in the comment earlier (replacing the word schema with database as you have separate databases), Foreign key reference is not possible in different databases. However you can apply join in tables from different databases. To access data from any database you just need to update queries with database name like database.table_name
. Just make sure the user has permission for both databases.
You will not be able to maintain the foreign key constraint at database level but you can create the column which stores the value of referenced column in another database (only storing the value not actually referencing). Later while retrieval use this column for join. Here is the example:
Suppose there are 2 databases organization
and broker
. And user some_user_name
has permissions to both databases. Let us create a table users
in broker
database:
CREATE TABLE "users" (
"user_id" INT NULL,
"user_name" VARCHAR(50) NULL
);
Insert a dummy record:
INSERT INTO users (user_id, user_name) values (1, 'Kamal');
Now, Let us create table in organization
database:
CREATE TABLE "app_log" (
"log_id" INT NULL,
"log_message" VARCHAR(100) NULL,
"user_id" INT NULL,
"log_date" DATETIME NULL
);
Insert a dummy record:
INSERT INTO app_log ("log_id", "log_message", "user_id", "log_date") VALUES ('1', 'sample log message', '1', '2018-01-26T06:50:48.000');
Now, we can use join query on user_id
column as:
SELECT u.user_name, l.log_message
FROM broker.users u INNER JOIN organization.app_log l ON u.user_id = l.user_id
WHERE l.log_date >= CONVERT(DATETIME, '2018-01-26', 102);
Hope this helps you!!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.