I have searched the questions but haven't been able to find an answer. Perhaps my wording may be wrong. My problem is as follows:
Given table Users :
ID code owner
1 777 James
2 432 George
3 111 Kale
And table Products :
ID product_name code
1 chair 777
2 table 777
3 fan 432
4 monitor 777
5 sofa 111
6 bed 111
I need a query that fetches N number of rows from table Users and then fetches all rows from table Products that have a code matching the code of Any row fetched previously.
Is this possible in SQL Server? Is it optimal?
For above example if i fetch first 2 rows (owners James and George) I should get all products with code 777 and 432.
Yes it is a common thing, called "Joins"
for example this would give you the answer:
Select products.product_name,users.owner FROM products LEFT JOIN users ON products.code=users.code
You can read more about JOINS here: https://www.w3schools.com/sql/sql_join.asp
To select the first n (here 2 ) users use TOP
. Put that in a subquery and LEFT JOIN products
on the common code to it.
SELECT *
FROM (SELECT TOP 2
*
FROM users
ORDER BY id) u
LEFT JOIN products p
ON p.code = u.code;
If you want to make users, that don't have at least one product, disappear you can replace the LEFT JOIN
by an INNER JOIN
.
Try this with Inner join :
Select products.product_name,users.owner FROM products inner JOIN users ON products.code=users.code
where users.code in (777,432)
Create table #Users
(
Id int Identity(1,1),
Code varchar(100),
Owner varchar(100)
)
Create table #Products
(
Id int Identity(1,1),
ProductName varchar(100),
Code varchar(100)
)
insert Into #Users(Code,Owner)
Select '777','James'
insert Into #Users(Code,Owner)
Select '432','George'
insert Into #Users(Code,Owner)
Select '111','Kale'
insert Into #Products(ProductName,Code)
Select 'Chair','777'
insert Into #Products(ProductName,Code)
Select 'Table','777'
insert Into #Products(ProductName,Code)
Select 'fan','432'
insert Into #Products(ProductName,Code)
Select 'monitor','777'
insert Into #Products(ProductName,Code)
Select 'Sofa','111'
insert Into #Products(ProductName,Code)
Select 'bed','111'
select * from #products
select * from #Products Left join #Users on #Users.Code=#Products.Code Where Owner in ('James','George')
This works even if code is not unique;
select * from Products where code in
(
select top 2 code from users order by id
)
Replace 2 with the relevant N
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.