mysql check if field value exists in another table - mysql

TABLE PRODUCTS
ProductID | ProductCode | SampleRefNum
1 a1
2 b2
3 c2
TABLE STOCK LIST
StockListID | ProductCode | SampleRefNum | QTY
1 a1 10
2 b2 10
3 j100 25
I have to 2 tables. The products tables is the current products on the site.
Stock list table is a list uploaded from the POS system , with products and their quantities.
Products either have a ProductCode or SampleRefNum .
I am trying to generate a list off all items in the product table that do not have a matching ProductCode or SampleRefNum in the stock list table. in the following e.g the query should return ProductID 3 .
I'm trying to do this with a query , instead of looping and checking results in PHP.

Try JOIN these two tables and take products with ProductCode or SampleRefNum is null from STOCK_LIST
select t1.* from PRODUCTS as t1
left join STOCK_LIST as t2 on t1.ProductID = t2.StockListID
where (t2.ProductCode IS NULL or t2.SampleRefNum is NULL)

You can use left join for correct your result.
SELECT p.* FROM products AS p
LEFT JOIN stockList AS s
ON p.productID = s.stockListId
OR p.sampleRefNum = s.sampleRefNum;

Select productId from Products where productId NOT IN(Select p.productId From Products p
INNER JOIN Stocklist s ON ( p.ProductCode=s.ProductCode || p.SampleRefNum=s.SampleRefNum));
I guess that productId and Stocklist Id are not related to each other they are just primary keys of two different tables.
So try above query.
If my guess is wrong comment the same in detail.

select table1.id table2.id from table1,table2 where tpl1.id=tpl2.id
after that check num_rows of return data if total is 0 that mean no things

This is the correct answer. It was part right by #Ye Win and 웃웃웃웃웃
SELECT * FROM products AS p
LEFT JOIN stock_list AS s
ON p.ProductCode = s.ProductCode OR p.SampleRefNum = s.SampleRefNum
WHERE (s.ProductCode IS NULL AND p.ProductCode IS NOT NULL OR s.SampleRefNum IS NULL AND p.SampleRefNum IS NOT NULL)

Related

MYSQL - Query to get values from one table if the value doesn't exist in another table

I'm struggling with a query. I need to create a view based on this query.
I've got 3 tables: seller, item, seller_item
Seller table
name
id
S1
1
S2
2
S3
3
Item table
name
id
price
I1
1
50
I2
2
100
Seller_Item table
seller_id
item_id
price
1
1
75
2
1
25
View I'd like to obtain
nome
item
price
S1
I1
75
S1
I2
100
S2
I1
25
S2
I2
100
S3
I1
50
S3
I2
100
Basically, if the item is not present in the table seller_item I want to insert the default value coming from the item table otherwise the one from the seller_item table.
I was able to achieve something similar using WHERE NOT EXIST, but only when I ask for a specific seller id, instead, here, I want to have the list of all the sellers with all items.
Thank you.
----- SOLUTION -----
Thank you for your quick answers.
Just few minutes after I posted the question I found the solution. It was a lot more verbose than what I was able to find thanks your suggestions.
The final query (with all the values I need) is this one:
SELECT
S.name AS name,
I.name AS item,
IF(SI.visible = 0, SI.visible, I.visible) AS visible,
IF(COALESCE(SI.price, 0) = 0, I.price, SI.price) AS price FROM seller S JOIN item I LEFT JOIN seller_item SI ON S.id = SI.seller_id AND I.id = SI.item_id ORDER BY 1, 2
Thank you again!
You can use CROSS JOIN and COALESCE function.
The query is as follows:
SELECT
s.name nome, i.name item, COALESCE(si.price, i.price) price
FROM
Seller s CROSS JOIN Item i
LEFT OUTER JOIN Seller_Item si
ON s.id=seller_id AND i.id=item_id
ORDER BY 1, 2
Fiddle
You could try using a corrso join for get all the combination between item and seler and the join the seller:iem ..
when the join match use the seller price otherwise use the imte price
select seller.name
, item.name
case when seller_item.item_id is null then item.price else seller_item.price
from seeler
cross join item
left join seller_item on seller_item.item_id = item.id
Hope the below query is what you are looking for
SELECT
s.name as name,
i.name as item,
IFNULL(si.price, i.price) as price
FROM item i
LEFT JOIN seller_item si ON i.id = si.item_id
LEFT JOIN seller s ON s.id = si.seller_id

Select between range of values in 2 tables

I have 2 tables
-- Purchases --
Id | IdProvider | Date | Observations
and
-- PurchasesDetails --
Id | IdProduct | Quantity | Price
where Purchases.Id = PurchasesDetails.Id
I want to make a SQL query where it returns all the purchases between a range of price (The price info is on PurchasesDetails table -> Quantity*Price)
For example: Get all the purchases that costed more than 0$ but less than 500$
I've tried this:
SELECT * FROM Purchases INNER JOIN PurchasesDetails ON Purchases.Id = PurchasesDetails.Id WHERE Purchases .Id sum(PurchasesDetails.Price*PurchasesDetails.Quantity) BETWEEN 0 AND 500
But it doesn't work. Seems like I'm missing a condition to link up all the PurchasesDetails with the same Id
I think it's a really easy task but I'm stuck there for few hours so all the help are welcome!!
Is this what you want?
SELECT p.*,
SUM(pd.Price * pd.Quantity) as purchase_total
FROM Purchases p INNER JOIN
PurchasesDetails pd
ON p.Id = pd.Id
GROUP BY p.Id
HAVING purchase_total BETWEEN 0 AND 500;
Note that SELECT p.* is fine with GROUP BY p.id, assuming that id is unique in Purchases.

How to reduce query time of the sql statement,mysql

Here is the sql(mysql):
Table product and product_sale_app
it will pass in two parameters,appkey is the attribute of table product_sale_app;category is the attribute of table product.I need get effect_date,product_id,name from table product and use the above conditions.
SELECT effect_date,
product_id,
name
FROM product
WHERE product_id IN
(SELECT product_id
FROM product_sale_app
WHERE appkey =88888
AND product_id IN
(SELECT product_id
FROM product
WHERE category =1 ) )
Instead of sub queries, JOIN the tables using product_id and then put conditions inside the WHERE clause.
Try the following:
SELECT p.effect_date,
p.product_id,
p.name
FROM product AS p
JOIN product_sale_app AS psa ON psa.product_id = p.product_id
WHERE p.category = 1 AND psa.appkey = 88888

Check if matching record exists in joined table

I have two tables: categories and prodvscats
categories prodvscats
id | id
title | categories_id
each table has some rows for example:
categories prodvscats
categ1 | categ1
categ2 | categ2
categ3
categ4
I would like to return all categories but I want to know which of them are existing in the prodvscats table.
Desired result:
title boolean variable exists
categ1 | 1
categ2 | 1
categ3 | 0
categ4 | 0
I tried with join but it returns only the first two rows. Maybe it needs something like case but I don't know how to do.
SELECT categories.id, categories.title
FROM categories
INNER JOIN prodvscats ON prodvscats.categories_id = categories.id
ORDER BY id
Use LEFT JOIN to join the two tables. This will return all rows including those where category does not exist in the other table. Then use GROUP BY to consolidate categories and COUNT to determine if match(es) exist:
SELECT
categories.id,
categories.title,
CASE WHEN COUNT(prodvscats.id) = 0 THEN 0 ELSE 1 END AS product_exists
FROM categories
LEFT JOIN prodvscats ON categories.id = prodvscats.categories_id
GROUP BY categories.id, categories.title
Try like this
SELECT categories.id, categories.title,
IF(prodvscats.categories_id IS NULL, '0', '1') AS exists_value
FROM categories
LEFT JOIN prodvscats ON prodvscats.categories_id = categories.id
ORDER BY id

Complex query with many joins

I am trying to make one query, to get some statistic data from database.
My tables structure described here:
PRODUCTS
id | price | buy_price | vendor_code | ...
ORDERS
id | shipping_method_id | ...
ORDER_ITEMS
id | order_id | product_id | quantity | ...
SHIPPING_METHODS
id | cost | ...
SUPPLIERS
id | code | ...
I want to get data like this. In words, I am making reports on Product total income, expenses and quantity of buys in my ecommerce, and want them to group by supplier. I wrote this sql:
SELECT orders.id,
suppliers.code,
COUNT(products.id)*items.quantity buys,
SUM(products.price*items.quantity + shipping_methods.cost) sales,
SUM(products.buy_price*items.quantity) expenses
FROM `orders` orders
INNER JOIN `order_items` items ON items.order_id = orders.id
INNER JOIN `products` products ON items.product_id = products.id
INNER JOIN (SELECT DISTINCT suppliers.code FROM `suppliers`) suppliers
ON products.vendor_code LIKE CONCAT(suppliers.code, '%%')
INNER JOIN `shipping_methods` shipping_methods ON orders.shipping_method_id = shipping_methods.id
WHERE (
orders.delivery_date_to BETWEEN '2011-11-18' AND '2011-11-19'
)
GROUP BY suppliers.code, orders.id
ORDER BY buys DESC
this returns to me this data:
order_id code buys sales expenses
85 SB 4 1504 1111.32
84 VD 2 496 350.82
60 lg 2 1418 1052.31
88 SB 1 376 277.83
When I change GROUP BY suppliers.code, orders.id to GROUP BY suppliers.code, it returns almost correct data, I mean data is grouped by code, but counting is wrong. Admit that sales and expenses are correct
order_id code buys sales expenses
85 SB 8 1880 1389.15
60 lg 2 1418 1052.31
84 VD 2 496 350.82
If u see SB counted total 8 sales, but really there are only 5, as u can see in previous table. I'm sure I missed something in my query, but cant understand how to correct this.
PS field order_id are unused in my further scripts, I use it because django's Model.objects.raw() query does need to have primary key in result, don't really understand why
try this query.
SELECT t1.code, SUM(t1.buys), SUM(t1.sales) FROM (
SELECT orders.id,
suppliers.code,
COUNT(products.id)*items.quantity buys,
SUM(products.price*items.quantity + shipping_methods.cost) sales,
SUM(products.buy_price*items.quantity) expenses
FROM `orders` orders
INNER JOIN `order_items` items ON items.order_id = orders.id
INNER JOIN `products` products ON items.product_id = products.id
INNER JOIN (SELECT DISTINCT suppliers.code FROM `suppliers`) suppliers
ON products.vendor_code LIKE CONCAT(suppliers.code, '%%')
INNER JOIN `shipping_methods` shipping_methods ON orders.shipping_method_id = shipping_methods.id
WHERE (
orders.delivery_date_to BETWEEN '2011-11-18' AND '2011-11-19'
)
GROUP BY suppliers.code, orders.id
ORDER BY buys DESC
) AS t1
GROUP BY t1.code
Edit: I've forgotten SUM() parts. Just added, please retry if you've already tried.