How to Select Data From Multiple Tables using inner join statment? - sql

I have three tables
Products Table :
ID
GeneralStockEnabled
RetailerID
Sources Table
ID
Name
RetailerID
and
ProductInventory Table
ProductID
SourceID
Stock
The user will pass both the #RetailerID and #ProductID in my Stored Procedure.
How Can I select All the sources for particular retailer and attach the stock value coming from the product inventory table to those sources exists in the product inventory table for a particular product id and also select the value of GeneralStockEnabled for that product? . Even I my product has no stocks, I still want to be able to retrieve all the sources for that retailer?.
Any Help is appreciated.
I have this SQL right now :
SELECT S.ID AS SourceID,S.Name AS SourceName,PIN.Stock
FROM Sources S
LEFT OUTER JOIN ProductInventory PIN
ON (S.ID = PIN.SourceID)
WHERE S.RetailerID = 1
AND PIN.ProductID = 1
but since my product inventory table has no records now. It is not selecting the left part which are the sources in this case.

try something like this:
select s.*, pr.Stock, p.GeneralStockEnabled
from sources s join
Products p on s.RetailerId = p.RetailerId left outer join
ProductInventory pr on pr.ProductId = p.Id
where s.RetailerId = #RetailerId and p.id = #ProductId

You can use joins for the same
http://www.w3schools.com/sql/sql_join.asp

Related

I want to do inner join of some colums but still show the other colums if thats possible

basically i have a quest to do where i have to get all the details (product_purchase,price_history ,product colums that are name,type,id and price)from just searching for a product id.i basically did
select price_history.product_id, product.id, product_purchase.product_id from ((price_history
inner join product on price_history.product_id = product.id)
inner join product_purchase on price_history.product_id = product_purchase.product_id);
right now it just gives me the product id from product_purchase price_history and the id from product and i wanted it to show all the other colums from the 3 tables and want to have an option where i can do an input of the id something like
where product.id= %s
Try this.
SELECT *
FROM price_history
INNER JOIN product
ON price_history.product_id = product.id
INNER JOIN product_purchase
ON price_history.product_id = product_purchase.product_id
WHERE product_id = %substitutedParameter%
But, as you will see, SELECT * gives you some redundant columns. It's good practice to name the columns you want in your SELECT.... something like this, I guess.
SELECT price_history.product_id,
product.description,
product_purchase.vendor
...

Deleting data from one table if the reference doesn't exist in two other tables

I managed to import too much data into one of my database tables. I want to delete most of this data, but I need to ensure that the reference doesn't exist in either of two other tables before I delete it.
I figured this query would be the solution. It give me the right result on a test database, but in the production environment it returns no hits.
select product
from products
where 1=1
and product not in (select product from location)
and product not in (select product from lines)
You are getting no results/hits it means that you table location and/or lines having the null values in the product column. in clause failed if column having null value.
try below query just added the null condition on the top of your shared query.
select product from products
where 1=1
and product not in ( select product from location where product is not null)
and product not in ( select product from lines where product is not null)
Use EXISTS instead of IN which is more efficient
DELETE FROM products WHERE
NOT EXISTS
(
SELECT
1
FROM [Location]
WHERE Product = Products.Product
) AND
NOT EXISTS
(
SELECT
1
FROM lines
WHERE Product = Products.Product
)
Try this..
DELETE FROM Products where not exists
(select 1 from Location
join lines on lines.Product = Location.Product
and Location.Product = Products.Product
);
It's difficult to tell from your post why the query would return results in the test database but not production other than there is different data or different structures. You might try including the DDL for the participating tables in your post so that we know what the table structures are. For example, is the "product" column a PK or a text name?
One thing that does jump out is that your query will probably perform poorly. Try something like this instead: (Assuming the "product" column is a PK in Products and FK in the other tables.)
Select product
From Products As p
Left Outer Join Location As l
On p.product = l.product
And l.product is null
Left Outer Join Lines as li
On p.product = li.product
And li.product is null;
This simple set based approach may help ...
DELETE p
FROM products p
LEFT JOIN location lo ON p.product = lo.product
LEFT JOIN lines li ON p.product = li.product
WHERE lo.product IS NULL AND li.product IS NULL

SQL Beginner: Getting items from 2 tables (+grouping+ordering)

I have an e-commerce website (using VirtueMart) and I sell products that consist child products. When a product is a parent, it doesn't have ParentID, while it's children refer to it. I know, not the best logic but I didn't create it.
My SQL is very basic and I believe I ask for something quite easy to achieve
Select products that have children.
Sort results by prices (ASC/DSC).
SELECT * FROM Products INNER JOIN Prices ON Products.ProductID = Prices.ProductID ORDER BY Products.Price [ASC/DSC]
Explanation:
SELECT - Select (Get/Retrieve)
* - ALL
FROM Products - Get them from a DB Table named "Products".
INNER JOIN Prices - Selects all rows from both tables as long as there is a match between the columns in both tables. Rather, JOIN DB Table "Products" with DB Table "Prices".
ON - Like WHERE, this defines which rows will be checked for matches.
Products.ProductID = Prices.ProductID - Your match criteria. Get the rows where "ProductID" exists in both DB Tables "Products" and "Prices".
ORDER BY Products.Price [ASC/DSC] - Sorting. Use ASC for Ascending, DSC for Descending.
This table design is subpar for a number of reasons. First, it appears that the value 0 is being used to indicate lack of a parent (as there's no 0 ID for products). Typically this will be a NULL value instead.
If it were a NULL value, the SQL statement to get everything without a parent would be as simple as this:
SELECT * FROM Products WHERE ParentID IS NULL
However, we can't do that. If we make the assumption that 0 = no parent, we can do this:
SELECT * FROM Products WHERE ParentID = 0
However, that's a dangerous assumption to make. Thus, the correct way to do this (given your schema above), would be to compare the two tables and ensure that the parentID exists as a ProductID:
SELECT a.*
FROM Products AS a
WHERE EXISTS (SELECT * FROM Products AS b WHERE a.ID = b.ParentID)
Next, to get the pricing, we have to join those two tables together on a common ID. As the Prices table seems to reference a ProductID, we can use that like so:
SELECT p.ProductID, p.ProductName, pr.Price
FROM Products AS p INNER JOIN Prices AS pr ON p.ProductID = pr.ProductID
WHERE EXISTS (SELECT * FROM Products AS b WHERE p.ID = b.ParentID)
ORDER BY pr.Price
That might be sufficient per the data you've shown, but usually that type of table structure indicates that it's possible to have more than one price associated with a product (we're unable to tell whether this is true based on the quick snapshot).
That should get you close... if you need something more, we'll need more detail.
use the below script if you are using ssms.
SELECT pd.ProductId,ProductName,Price
FROM product pd
LEFT JOIN price pr ON pd.ProductId=pr.ProductID
WHERE EXISTS (SELECT 1 FROM product pd1 WHERE pd.productID=pd1.ParentID)
ORDER BY pr.Price ASC
Note :neither of your parent product have price in price table. If you want the sum of price of their child product use the below script.
SELECT pd.ProductId,pd.ProductName,SUM(ISNULL(pr.Price,0)) SUM_ChildPrice
FROM product pd
LEFT JOIN product pd1 ON pd.productID=pd1.ParentID
LEFT JOIN price pr ON pd1.ProductId=pr.ProductID
GROUP BY pd.ProductId,pd.ProductName
ORDER BY pr.Price ASC
You will have to use self-join:
For example:
SELECT * FROM products parent
JOIN products children ON parent.id = children.parent_id
JOIN prices ON prices.product_id = children.id
ORDER BY prices.price
Because we are using JOIN it will filter out all entries that don't have any children.
I haven't tested it, I hope it would work.

SQL query on link table where results must contain certain value

SQL Server 2005.
I've a link table of Products and Attributes associated with them. I'm doing a search along the lines of:
select distinct ProductId from productattributelink where
attributeid in (25,5,44,46)
But I want to make sure that each productid is also associated with an attributeId of 10.
So in longhand the query would be: Show me all the product Ids that have the following attributeids (25,5,44,46) but also have attributeid of 10.
I've a feeling this is really obvious but is eluding me.
select distinct p.ProductId from product p
inner join productattributelink pa1 on pa1.ProductId = p.ProductId
inner join productattributelink pa2 on pa2.ProductId = p.ProductId
where pa1.attributeid IN(25,5,44,46) and pa2.attributeid = 10
You should join the table to itself:
select distinct ProductId from productattributelink p1
JOIN productattributelink p2 ON p1.ProductId = p2.ProductId
where p1.attributeid in (25,5,44,46) AND p2.attributeid = 10

SQL Query to fetch all product categories and whether the product is in it

I have three tables. Product, product categories and product category links. The links table is there as a product can be in more than one category.
What I am trying to achieve is a list of ALL the categories with an additional field which states whether for that specific product id, if the product is in that category.
SELECT *, l.product_id as checked FROM `ProductCategories` LEFT JOIN ProductCategoriesLink l ON l.category_id = ProductCategories.id WHERE ( l.product_id = 1 ) AND ( ProductCategories.id > 0 ) GROUP BY ProductCategories.id ;
However at the moment, this only retrieves the categories which the product is in.
Any advice appreciated.
SELECT
ProductCategories.*,
l.product_id IS NOT NULL AS ProductInCategory
FROM
ProductCategories
LEFT JOIN ProductCategoriesLink AS l ON
ProductCategories.id = l.category_id AND
l.product_id = 1
This makes use of the fact that when a LEFT JOIN is performed, at least one row is returned for every row on the left-hand table. If there weren't matching rows on the right-hand table, the columns from that table are all NULL.