Home > Net >  How do I write queries for data in tables that already contain relationships?
How do I write queries for data in tables that already contain relationships?

Time:06-29

I am using SQL Server and SSMS.

I have a table called PersonsTable:

   PersonID  FirstName   Surname  Age
   ----------------------------------
    1         Hansen      Ola      30
    2         Svendson    Tove     23
    3         Pettersen   Kari     20

I also have a table called OrdersTable:

OrderID OrderNumber PersonID
----------------------------
1               77895   3
2               44678   3
3               22456   2
4               24562   1
  • The PersonID column in the PersonsTable table is the PRIMARY KEY.
  • The PersonID column in the OrdersTable table is a foreign key.

How do I write a query that returns the FirstName and the OrderNumber values?

CodePudding user response:

SELECT OT.OrderNumber,PT.FirstName    
FROM OrdersTable AS OT
JOIN PersonsTable AS PT ON OT.PersonID=PT.PersonID  
  • Related