I have two tables I want to join in SQL Server.
One houses call data and has a unique id Login_ID. This table does not contain the employees name.
The other table does not have a unique id for employees.
What I need to do is join these two tables so I can see call data and ticket data simultaneously by employee.
Unfortunately, there is no correlating column for Login_ID in the ticket table to link employee data.
Example of call data table:
Login_ID | Calls | CallTime | Date |
00000001 | 34 | 349874 | 030317 |
Example of ticket table:
Name | Ticket_Num | Date |
Some Emp | 5456465434 | 030317 |
So what happens is: anytime someone changes their name, they basically have a new ID in this table. It's awful.
I only need the data from around 18 employees.
My question is: how can I associate the Login_ID with the ticket table?
Hopefully I made this clear enough!
You should to store the association using what is known as a Foreign Key. This will ensure the integrity of the relationships between your data and can help optimize your queries when you are trying to pull associated data from different tables.
A FOREIGN KEY is a key used to link two tables together.
A FOREIGN KEY is a field (or collection of fields) in one table that
refers to the PRIMARY KEY in another table.
The table containing the foreign key is called the child table, and
the table containing the candidate key is called the referenced or
parent table.
You get query associated date using a join.
If you have a 1:1 relationship you add Login_ID as a field to your ticket table and you can join your table on Login.Login_ID = Tickets.Login_Id.
Alter Table Tickets
Add Login_ID int not null Constraint "FK_Tickets_LoginId" References Tickets(Login_Id)
// USAGE:
Select * from Logins Join Tickets on Logins.Login_ID=Tickets.Login_Id where Login_ID=#LoginId
If you can't modify either table then you can create a new table, perhaps Logins2Tickets which will contain two fields Login_ID and Ticket_Num
You can then join your Logins to Logins2Tickets on Login.Login_ID = Tickets.Login_Id and join Logins2Tickets to Tickets on Logins2Tickets.Ticket_Num = Tickets.Ticket_Num
Create Table Logins2Tickets
(
Login_ID int not null constraint "FK_Logins2Tickets_Login_ID" References Logins(Login_Id)
Ticket_Num bigint not null constraint "FK_Logins2Tickets_Ticket_Num" References Tickets(_Login_ID)
)
// USAGE:
Select *
From
Logins l Join Logins2Tickets lt
on l.Login_ID=lt.Login_ID
Join Tickets t
on lt.Ticket_Num=t.Ticket_Num
WHERE Login_ID=#LoginId
Related
I have two database tables "Users" and "Transactions" with many to many relationship between them. I have created a Junction Model which will have two foreign key columns (UserId, TransactionId) and will keep track of the associations. The Transaction table has two columns where I keep track of who the sender is and who the recipient is (senderAccount, recipientAccount).
Question 1: since each Transaction belongs to two users which are the sender and recipient, do I also need to specify both senderId and recipientId inside the junction model instead of just userId?
Note: my confusion is from the two foreign key columns(UserId and TransactionId) inside the junction model. I understand that there is only one transaction and you can reference that transaction by its id in the junction model, but each transaction is also owned by two users (sender and recipient) shouldn't we reference both of the users inside the junction model?
Question 2: if my analogy up here is correct, how would you reference both senderId and recipientId inside the junction model?
Question 3: if my analogy up here is incorrect, please help me understand how you would go about referencing both users in the junction model.
Users table
id | username |
—--+----------+
1 | ijiej33 |
Transactions table
id | transactionId | senderAccount | recipientAccount | Amount |
—--+---------------+---------------+------------------+--------+
1 | ijiej33 | A | B | 100 |
userTransaction table (junction model)
userId | TransactionId |
-------+---------------+
| |
As I explained as a comment in your question from yesterday, you do not have a many-to-many relationship between transactions and users. You have two many-to-one relationships from transactions to users. You therefore do not need a join table.
Model it thus:
create table users (
user_id serial primary key,
user_name text not null unique
);
create table transaction (
transaction_id serial primary key,
sender_account int not null references users(user_id),
recipient_account int not null references users(user_id),
amount numeric
);
Let's say I have two tables and I'm doing all the operations in .NET Core 2 Web API.
Table A:
Id,
SomeValue,
TeamName
Table B:
Id,
Fk_Id_a (references Id in table A),
OtherValue,
TeamName
I can add and get records from table B indepedently.
But for every record in Table B TeamName has to be the same as for it's corresponidng Fk_Id_a in Table A.
Assume these values comes in:
{
"Fk_Id_a": 3,
"SomeValue": "test val",
"TeamName": "Super team"
}
Which way would be better to check it in terms of performance? 1ST way requires two connections, when 2nd requires storing some extra keys etc.
1ST WAY:
get record from Table A for Fk_Id_a (3),
check if TeamName is the same as in coming request (Super team),
do the rest of the logic
2ND WAY:
using compound foreign keys and indexes:
TableA has alternate unique key (Id, TeamName)
TableB has foreign compound key (Fk_Id_a, TeamName) that references TableA (Id, TeamName)
SQL SCRIPT TO SHOW:
ALTER TABLE Observation
ADD UNIQUE (Id, PowelTeamId)
GO
ALTER TABLE ObservationPicturesId
ADD FOREIGN KEY(ObservationId, PowelTeamId)
REFERENCES Observation(Id, PowelTeamId)
ON DELETE CASCADE
ON UPDATE CASCADE
EDIT: Simple example how the tables might look like. TeamName has to be valid for FK referenced value in Table A.
Table A
ID | ObservationTitle | TeamName
---------------------------------------
1 | Fire damage | CX_team
2 | Water damage | CX_team
3 | Wind damage | Dd_WP3
Table B
ID | PictureId | AddedBy | TeamName | TableA_ID_FK
-----------------------------------------------------
1 | Fire | James | CX_team | 1
2 | Water | Andrew | CX_team | 1
3 | Wind | John | Dd_WP3 | 3
Performance wise, the 2nd option would be faster because there is no comparison to check (the foreign key will force that they match when inserting, updating or deleting) when selecting the rows from the table. It would also make a unique index on table A.
That being said, there is something very fishy about the structure you mention. First of all why is the TeamName repeated in table B? If a row in table B is "valid" only when the TeamName match, then you should enforce that no row should be inserted with a different TeamName, throught the ID foreign key (and not actually storing the TeamName value). If there are records on table B that represent another thing rather than the entity that is linked to table A then you should split it onto another table or just update the foreign key column when the team matches and not always.
The issue is that you are using a foreign key as a partial link, making the relationship valid only when an additional condition is true.
INSERT INTO customers (ID, NAME, AGE, ADDRESS, SALARY)
VALUES(3, 'sin', 21, 'bangalore', 10000);
INSERT INTO orders (orderid, orderno)
VALUES (3, 21);
Here ID is the primary key in the customer table, orderid is the primary key in the orders table.
I would like to know whether it is mandatory to add id as foreign key in orders table for performing SQL join?
It is not necessary to establish a foreign key in order to perform an inner join of the customers and orders table. However, the question arises of what the significance of such a join operation would be without a foreign key.
Presumably the goal is to model some sort of relationship between customers and orders. Assuming the attributes listed comprise all of the attributes in the two tables, there is nothing establishing a relationship between customers and orders in the way the tables are defined. Adding a customerID field as a foreign key in the orders table would establish that relationship. Then, an inner join on the condition customers.ID = orders.customerID would associate the order information with the appropriate customer's information in the joined table.
My thought here that when you asking whether FK is needed or not, you accept by default that both working within the same domain, and this is not a valid assumption, in brief
The inner join is used with the reading (query) of data, whereas FK
exists to maintain the integrity of data during a different kind of operations such as insert, update and delete.
In my opinion, the correct answer should be that both FK and inner join are not relevant.
I will use the below tables to explain the difference between both
Customers
| id | name |
|:------------|---------:|
| 1 | Gabriel |
| 2 | John |
| 3 | Smith |
Orders
| order_id |customer_id|
|:-----------|---------: |
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
Inner Join,
is used during query for example according to the above, let's say you want to query all orders made by a specific customer.
select * from customers, orders
where customer.id=orders.customer_id
and customer.id=2
according to our tables, you will end up with one order number (4) for the customer (John)
Foreign Key
While the inner join used during the query, the Foreign Key is used to apply policies over the major DML operations (Insert, update and delete).
below are examples of operations that will fail for violating the FK constraint
Insert into orders(order_id,customer_id) values(5,7)
this operation will fail because no customer exists with id (7) in the Customer table, the same will apply for the update operation.
Also if the FK enabled the On delete cascade or On update cascade
this will delete or update child rows when trying to delete or update the master table, example deleting the customer Gabriel will delete orders 1,2 and 3.
I Have table three tables:
The first one is emps:
create table emps (id number primary key , name nvarchar2(20));
The second one is cars:
create table cars (id number primary key , car_name varchar2(20));
The third one is accounts:
create table accounts (acc_id number primary key, woner_table nvarchar2(20) ,
woner_id number references emps(id) references cars(id));
Now I Have these values for selected tables:
Emps:
ID Name
-------------------
1 Ali
2 Ahmed
Cars:
ID Name
------------------------
107 Camery 2016
108 Ford 2012
I Want to
Insert values in accounts table so its data should be like this:
Accounts:
Acc_no Woner_Table Woner_ID
------------------------------------------
11013 EMPS 1
12010 CARS 107
I tried to perform this SQL statement:
Insert into accounts (acc_id , woner_table , woner_id) values (11013,'EMPS',1);
BUT I get this error:
ERROR at line 1:
ORA-02291: integrity constraint (HR.SYS_C0016548) violated - parent key not found.
This error occurs because the value of woner_id column doesn't exist in cars table.
My work require link tables in this way.
How Can I Solve This Problem Please ?!..
Mean: How can I reference tables in previous way and Insert values without this problem ?..
One-of relationships are tricky in SQL. With your data structure here is one possibility:
create table accounts (
acc_id number primary key,
emp_id number references emps(id),
car_id number references car(id),
id as (coalesce(emp_id, car_id)),
woner_table as (case when emp_id is not null then 'Emps'
when car_id is not null then 'Cars'
end),
constraint chk_accounts_car_emp check (emp_id is null or car_id is null)
);
You can fetch the id in a select. However, for the insert, you need to be explicit:
Insert into accounts (acc_id , emp_id)
values (11013, 1);
Note: Earlier versions of Oracle do not support virtual columns, but you can do almost the same thing using a view.
Your approach should be changed such that your Account table contains two foreign key fields - one for each foreign table. Like this:
create table accounts (acc_id number primary key,
empsId number references emps(id),
carsId number references cars(id));
The easiest, most straightforward method to do this is as STLDeveloper says, add additional FK columns, one for each table. This also bring along with it the benefit of the database being able to enforce Referential Integrity.
BUT, if you choose not to do, then the next option is to use one FK column for the the FK values and a second column to indicate what table the value refers to. This keeps the number of columns small = 2 max, regardless of number of tables with FKs. But, this significantly increases the programming burden for the application logic and/or PL/SQL, SQL. And, of course, you completely lose Database enforcement of RI.
I have a table which has these columns:
Id (Primary Key): the id.
OwnerId (Foreign Key): the id of the owner, which resides in another table.
TypeId (Foreign Key): the type of thing this record represents. There are a finite number of types, which are represented in another table. This links to that table.
TypeCreatorId (ForeignKey): the owner of the type represented by TypeId.
SourceId (Foreign Key): this isn't important to this question.
I need to constrain this table such that for each Id, there can be only one of each TypeCreatorId. I hope that makes sense!
For SQL Server, you have two options:
create a UNIQUE CONSTRAINT
ALTER TABLE dbo.YourTable
ADD CONSTRAINT UNIQ_Id_TypeCreator UNIQUE(Id, TypeCreatorId)
create a UNIQUE INDEX:
CREATE UNIQUE INDEX UIX_YourTable_ID_TypeCreator
ON dbo.YourTable(Id, TypeCreatorId)
Basically, both things achieve the same thing - you cannot have two rows with the same (Id, TypeCreatorId) values.
Simply create a unique index on OwnerId and TypeCreatorId.
An example using MySQL (sorry, I don't use SQL Server):
alter table yourTable
add unique index idx_newIndex(OwnerId, TypeCreatorId);
Example. I'll just put here what would happen with this new unique index:
OwnerId | TypeCreatorId
--------+--------------
1 | 1
1 | 2 -- This is Ok
2 | 1 -- Ok too
2 | 2 -- Ok again
1 | 2 -- THIS WON'T BE ALLOWED because it would be a duplicate