简体   繁体   中英

How to apply join in 3 tables if 3rd does not have primary key?

How to join between three tables like i have three tables productoption, productsize and price and t3 do not have a primarykey but the problem is that the productsize tbl do not have a primary key

productoption innerjoin productsize innerjoin price

select * from Prices
select * from Product
select * from ProductOption
select * from ProductSize

select PriceFor, SourceID, MainPrice 
from Prices 
where PriceFor = 2 
  and SourceID in (select ProductOptionID from ProductOption where ProductId=7)
select * from Product
select ProductID, ProductName +' - '+ Convert(varchar(5),ProductID) as C
from Product

need inner join btw productoption > productsize and productoption > price

Well lacking a primary key does not stop you doing a join. The join can be any column you choose. The following sytax will join 3 tables

SELECT A.*, B.*, C.*
FROM
   A
   INNER JOIN
   B
   INNER JOIN
   C
   ON B.Col1 = C.Col2
   ON A.Co3 = B.Col4

However the performance may not be good if you dont have indexes which cover the columns used in the joins. I presume your question is how to join 3 tables? Note the order of the "ON"s is nested, in to out, The order of the tables (in the ON condition) is the same order as they appear in the initial part join statement. Can be confusing

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM