开发者

SQL Join 2 tables

I have two tables one named Person, which contains columns ID and Name and the second one, named Relation, which contains two columns, each of which contains an ID of a Person. It's about a relation between customer and serviceman. I'd like to Join these two tables so that I'll have names of people in every relation. Is it possible to write this query with some kind of joining?

EDIT::

I must do something wrong, but it's not working. I had tried a lot of forms of so looking queries, but I had been only getting one column or some errors. It's actually the school task, I have it already done (with different JOIN query). Firstly I had been trying to do this, but I'd failed: It seems to be very common situation, so I don't know why it's too complicated for me..

Here are my tables:

CREATE TABLE Oprava..(Repair) (  
  KodPodvozku INTEGER PRIMARY KEY REFERENCES Automobil(KodPodvozku),  
  IDzakaznika..(IDcustomer) INTEGER REFERENCES Osoba(ID),  
  IDzamestnance..(IDemployee) INTEGER REFERENCES Osoba(ID)  
);

CREATE TABLE Osoba..(Person) (  
  ID INTEGER CONSTRAINT primaryKeyOsoba PRIMARY KEY ,  
  Jmeno..(Name) 开发者_运维知识库VARCHAR(256) NOT NULL,  
  OP INTEGER UNIQUE NOT NULL  
);

It's in Czech, but the words in brackets after ".." are english equivalents. PS: I am using Oracle SQL.


Assuming your tables are:

persons:   (id, name)
relations: (customer_id, serviceman_id)

Using standard SQL:

SELECT p1.name AS customer_name, 
       p2.name AS serviceman_name
FROM persons p1 
     JOIN relations ON p1.id=relations.customer_id
     JOIN persons p2 ON relations.serviceman_d=p2.id;

Further explanation

The join creates the following table:

p1.id|p1.name|relations.customer_id|relations.serviceman_id|p2.id|p2.name

Where p1.id=relations.customer_id, and p2.id=relations.serviceman_id. The SELECT clause chooses only the names from the JOIN.

Note that if all the ids from relations are also in persons, the result size would be exactly the size of the relations table. You might want to add a foreign key to verify that.


SELECT *
FROM Relation
INNER JOIN Person P1
ON P1.ID = Relation.FirstPersonID
INNER JOIN Person P2
ON P2.ID = Relation.SecondPersonID


SELECT p1.name AS customer, p2.name AS serciveman
FROM person p1, person p2, relation
WHERE p1.id=relation.customerid AND p2.id=relation.servicemanid


Person(ID, Name) Relation(ID)

You don't mention the other columns that relation contains but this is what you need:

Select name
from Person as p
join Relation as r
on p.ID = r.ID

This is an INNER JOIN as are most of the other answers here. Please don't use this until you understand that if either record doesn't have a relationship in the other table it will be missing from the dataset (i.e. you can lose data)

Its very important to understand the different types of join so I would use this as an opportunity.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜