find the record that holds the foreign key - sql

Let's say I have two tables, Product and Sale, Sale holds a foreign key to Product, so it's a one-to-many relationship with Product as one and Sale as many. How to write sql to get the Product of a Sale?

JOIN the two tables:
SELECT
*
FROM Product AS p
INNER JOIN Sale AS s ON s.ProductId = p.ProductId
WHERE s.SaleId = ...
Then you can specify a WHERE clause to filter on the Sale table, and SELECT whatever columns you want to select from the two tables.
You probably might need to have a look at the different types of JOINs:
A Visual Explanation of SQL Joins.

Related

SQL Server need to find suppliers who supply the most different products

I have two tables I need information from, Products and Suppliers. Both these tables have a SupplierID column I am trying to use to join them together to retrieve the right info.
The output I need is SupplierID and ContactName from the Suppliers table. The correct output should contain only two suppliers, so I attempted something like this, but ran into a conversion error converting nvarchar value to a data type int. I am not supposed to count how many products they supply but aggregate functions seem like the best method to me.
SELECT TOP 2 ContactName, COUNT(Products.SupplierID) AS Supply
FROM Products
LEFT JOIN Suppliers ON Suppliers.ContactName = Products.SupplierID
GROUP BY Products.SupplierID, Suppliers.ContactName
ORDER BY Supply;
I have tried many different queries but none will work. I am confused on how to join these tables without running into errors. All the products have a unique ProductID as well. The correct output should look something like this:
7 John Smith
12 John Sample
Both these tables have a SupplierID column I am trying to use to join them together to retrieve the right info
If so, you should be joining on that column accross tables.
Also, it is a good practice to use table aliases and prefix each column with the table it belongs to.
Another remark is that if you want suppliers that sell the most different products, then you want to order by descending count (not ascending).
Finally, if you want to left join, then you should start from the suppliers and then bring in the products, not the other way around.
Consider:
select top 2
s.SupplierID,
s.ContactName,
COUNT(*) as Supply
from Suppliers s
left join Products p on p.SupplierID = s.SupplierID
group by s.SupplierID, s.ContactName
order by Supply desc;
You're currently joining on two different fields:
on Suppliers.ContactName = Products.SupplierID
Presumably this should be as follows?
on Suppliers.SupplierID = Products.SupplierID

Joining tables on foreign key

I have the following three tables:
Product
Purchase (contains ProductID as foreign key)
Sale (contain ProductID as foreign key as well)
I want to form query joining these 3 tables where my result is the product name, purchased, and sold.
Product Name - (from Products table)
Purchased - (Number of occurences in Purchase table according to ProductID)
Sold - (Number of occurences in Sale Table according to ProductID)
Can you please set me on the right track by giving me hints and I'll complete by myself?
I'm betting this will get deleted...but hopefully you see this before it does. The following is really helpful in understanding the differences in the SQL JOINS. . This answer or Kyle's answers is all you need to solve your question.
Source: INNER JOIN, LEFT/RIGHT OUTER JOIN
As far as a hint, you need to use a join of some sort (join fundamentals).
A possible answer is below:
Select p.ProductName, pu.Purchased, s.Sold
From Products p
INNER JOIN Purchase pu on p.ProductID = pu.ProductID
INNER JOIN Sale s on s.ProductID = p.ProductID

how to get data in sql when a one table have more than one foriegn keys of a table

I have three tables in my database called supplier, materials, categories.
In the materials table it have a supplier id as foreign key and each material going with
three categories. I have keep that categories by using id of category table. So there are three fields in material table to keep ids of categories. It means the material table have three foreign keys of category table.
Now my problem is how to select data from material table using sql join with supplier and categories table.
You should be able to do something like this:
SELECT ...
FROM
supplier
JOIN materials ON
supplier.supplier_id = materials.supplier_id
JOIN categories ON (
materials.category_id1 = categories.category_id
OR materials.category_id2 = categories.category_id
OR materials.category_id3 = categories.category_id
)
But you should really reconsider the way you connect between materials and categories. This looks like a regular many-to-many relationship, that can be represented by a "junction" (aka "link") table in between these two tables. This would allow you to have unlimited categories per material.

Ensure in many-to-many relationship at least one relationship is primary

Sorry for the bad title, if you can think of a better one, let me know.
Many-to-many relationship using tables.
Product
ProductCategory
Category
In the ProductCategory table i have boolean column primarycategory
Each product must have a primary category.
I want to find all products in my database which don't have a primarycategory.
Note: I have assumed field names in tables other than the one you specified.
This should return a distinct list of product IDs that have no primary category. Bit fields in SQL server are numeric, so you can give them to the max() function.
select
pc.product
from
ProductCategory pc
group by
pc.product
having
max(pc.primarycategory) = 0
The above query assumes that all products have at least one category. If not, try the following:
select
pc.product
from
Product p
left join
ProductCategory pc on p.id = pc.product
group by
pc.product
having
max(isnull(pc.primarycategory, 0)) = 0
Assuming true = value 1, try this:
Select Product From Product p
Where Not Exists (Select * From ProductCategory
Where Product = p.Product
And primarycategory = 1 )
but if you have control over this database, Move the PrimaryCategory column to the Products table, (and populate it with the category identifier itself, not a boolean), that is where this belongs in a properly normalized schema...

Selecting products sold to a given set of customers

I have two tables, product and sold_record. product contains my list of products, while sold_record contains all of my transactions. How can I select a distinct list of products that both customer A and customer B bought?
If your sold_record table has a product id and customer id, then the query would be:
select distinct s1.product_id
from sold_record as s1, sold_record as s2
where s1.customer_id = "Customer A"
and s2.customer_id = "Customer B"
and s1.product_id = s2.product_id;
There may be a simpler way to do this using a join, but this should work.
Let's suppose table Product has a primary key ProdID, and table Sold a foreign key into Product by the same name as well as a Customer field (probably another foreign key into a third table Customer, but since you say there must be only two tables we'll assume a string that's the customer name, instead). Then:
Select DISTINCT Product.ProdID
From Product
Inner Join Sold SA On (Product.ProdID=SA.ProdID
AND SA.Customer='A')
Inner Join Sold SB On (Product.ProdID=SB.ProdID
AND SB.Customer='B')
will give you the ProdID in question (of course, you can get other columns from that table, too, we just have no idea what those columns might be;-).