nageeb
nageeb

Reputation: 2042

Select 1 row from table where foreign key table records exist

I've got two tables, Products and ProductImages with a one to many relationship between Products and ProductImages. I'm trying to work a query on on the Products table with a condition that the results contain only rows with matching records in the ProductImages table.

Products
----------
id (PK)

ProductImages
---------------
id (PK)
product_id (FK to Products)

The only way I can work it is with a subquery, but surely there must be a better/more efficient way.

Upvotes: 0

Views: 1066

Answers (4)

user1237118
user1237118

Reputation:

user join

SELECT * FROM Products INNER JOIN ProductImage  on 
Products.id  = ProductImage.product_id 

Upvotes: 2

Asif
Asif

Reputation: 2677

SELECT Products.* FROM Products
INNER JOIN ProductImages ON Products.id = ProductImages.id
and Products.Id = @ProductID // if required this condition

Upvotes: 0

juergen d
juergen d

Reputation: 204766

select * from products
where id in (select product_id from ProductImages)

Upvotes: 0

vearutop
vearutop

Reputation: 4062

SELECT p.* FROM Products AS p
INNER JOIN ProductImages AS pi ON p.id = pi.product_id
GROUP BY p.id

Upvotes: 2

Related Questions