SQL query in Mysql - mysql

I am using php and Mysql and need help to display UNIQUE results for a price comparison.
My tables are:
tblItems
ID | SKU | Shop | Name | Size
1 S1 Shop1 A S
2 S2 Shop1 B M
3 S3 Shop1 C L
4 S4 Shop2 A S
tblProductFeed
ID | SKU | Shop | Price
1 S1 Shop1 12
2 S2 Shop1 14
3 S3 Shop1 15
4 S4 Shop2 11
The idea is a price comparison.
I want to compare all records where Size='S'. But I only want to get the lowest price from tblProductFeed, and I only want one record where the price is lowest.
My thoughts are like:
Get SKU, Shop and Name from tblItems where Size='S'
Compare matching rows in tblProductFeed where SKU and Shop are matching
Get the lowest price from tblProductFeed
Display only one DISTINCT Name from TblItems and with the lowest price
Results:
Name | Price
A 11
B 14
C 15
Maybe my idea is bad, please correct me.
Before I decided to scrap data and build to tables my sql was like this, might help to get some inspiration.
SELECT tbl.*
FROM tblProductFeed tbl
INNER JOIN (SELECT Size
, MIN(Price) MinPrice
FROM tblProductFeed
WHERE Size = '". $str ."'
GROUP BY Size) tbl1
ON tbl1.Size = tbl.Size
WHERE tbl1.MinPrice = tbl.Price;

try this : to retrieve lowest price for data with size 'S'
select a.Name, a.Shop, b.Price as minprice from tblItems as a
inner join tblProductFeed as b on
a.id = b.id and
a.SKU = b.SKU and
a.Shop = b.shop
where a.size = 'S' and b.price in (select min(price) from tblProductFeed)
Result :
Or if you want to get all item with lowest price try this :
select name,min(price)minprice from
(select a.id, a.SKU, b.shop, a.name, a.size, b.Price from tblItems as a
inner join tblProductFeed as b on
a.id = b.id and
a.SKU = b.SKU and
a.Shop = b.shop
where b.price in (select min(price) from tblProductFeed group by price)) a
group by name
Result :

Related

How to get only the maximum values of a joined table?

I have items that can have many prices. I want a result table that has all the items itself and only the latest price of the item for a given region.
item
id
name
1
banana
2
apple
​
price
id
item_id
region
price
date
1
1
USA
10
1-1-2021
2
1
USA
20
2-1-2021
3
2
USA
30
1-1-2021
4
2
Canada
40
2-1-2021
​
result (should look like this)
id
name
region
price
date
1
banana
USA
20
2-1-2021
2
apple
USA
30
1-1-2021
I tried this but it returns all the rows from both tables.
select *
from item
LEFT JOIN price p on p.item_id = item.id
where p.created_at in (
select max(price.created_at)
from price
where p.id = price.id
)
and p.region = 'USA'
​
I fail to understand what I have to do to reduce the result table to only the rcords with the latest prices for each item.
Try this:
SELECT p.id, i.name, p.region, p.price, p.date
FROM price p
INNER JOIN (SELECT item_id, MAX(date) AS date FROM price GROUP BY item_id) t
ON t.item_id = p.item_id AND t.date = p.date
JOIN item i
ON p.item_id = i.id
WHERE p.region = 'USA'
Part of the reason your code did not work is that, in your WHERE clause, you are filtering by the maximum date of all the records in the price table.
This is a typical use-case for row_number():
select *
from item i left join
(select p.*,
row_number() over (partition by id order by created_at desc) as seqnum
from price p
where p.region = 'USA'
) p
on p.item_id = i.id and seqnum = 1;

how to get max rows from 2 transactional tables. MySQL

I have two mysql transactional tables and and two lookup tables. I want to select max(id) from each of the transactional tables, combine the results with lookup tables and combine into one row. I seem unable to find solutions so far. Here is my tables. Stocks and Prices are transactional while Vehicle and Models are lookup tables.
Vehicles table
id name
1 Toyota
2 Suzuki
Models table
id vehicle_id name
1 1 Corolla
2 2 Swift
3 1 Prado
4 2 Vitara
Stocks table
id vehicle_id model_id qty
1 1 1 50
2 2 2 77
3 1 1 40
4 2 2 30
Prices table
id vehicle_id model_id price
1 1 1 500
2 2 2 777
3 1 1 600
4 2 2 1000
Expected results
id vehicle_id model_id qty price vname mname
1 1 1 40 600 Toyota Corolla
2 2 2 30 1000 Suzuki Swift
Here is what I've tried among countless trials
select s.*, b.name vehicle, m.name model, p.price
from stocks s, vehicles b, models m, prices p
where s.id in (select max(id) id from stocks
where s.vehicle_id = b.id and s.model_id = m.id and s.vehicle_id = p.vehicle_id and s.model_id = p.model_id
group by vehicle_id, model_id)
order by id;
Running the above query doesn't give me what I want and it crushes the PC. I have to restart. How can I achieve the expected outcome?
If you are using MySQL 8 you can use window functions and common table expressions for latest(based on maximum id per vehicle and model group) prices and qty for vehicle and models
with pricescte as (select *,
rank() over (partition by vehicle_id,model_id order by id desc) AS price_rank
from prices),
stockcte as (select *,
rank() over (partition by vehicle_id,model_id order by id desc) AS stock_rank
from stocks)
select v.id,
v.name,
m.id as model_id,
m.name,
s.qty,
p.price
from vehicles v
join models m on v.id = m.vehicle_id
join stockcte s on v.id = s.vehicle_id
and m.id = s.model_id
join pricescte p on v.id = p.vehicle_id
and m.id = p.model_id
where s.stock_rank = 1
and p.price_rank = 1
DEMO
If you are not on latest version of MySQL < 8 you could use a query like
select v.id,
v.name,
m.id as model_id,
m.name,
s.qty,
p.price
from vehicles v
join models m on v.id = m.vehicle_id
join (
select *
from stocks st
where id = (
select max(id)
from stocks
where st.vehicle_id =vehicle_id
and st.model_id = model_id
)
) s
on v.id = s.vehicle_id
and m.id = s.model_id
join (
select *
from prices pr
where id = (
select max(id)
from prices
where pr.vehicle_id =vehicle_id
and pr.model_id = model_id
)
) p on v.id = p.vehicle_id
and m.id = p.model_id
DEMO

How can I retrieve Similar Orders In Mysql?

i need a query that should first look the oldest order which has status 0 (zero). and retrieves all the similar orders of that kind(matches exact total qty, itemSku and number of distinct items ordered).
***OrdersTable***
ID OrderNumber CustomerId Status created_at
1 123456 1 0 2018-01-01
2 234567 1 0 2018-01-02
3 345678 1 0 2018-01-03
4 456789 1 0 2018-01-04
***PurchasedProductsTable***
OrderId itemSku Qty
1 1000001 1
1 1000002 2
2 1000001 3
3 1000001 1
3 1000002 2
4 1000001 3
In the above table the query should first look at the oldest (created_at ASC) order (i.e with Id 1) having status 0 (in order table). and along with that order it should retrieves all the other orders that matches the same itemSku, qty and total distinct items count (in purchasedProducts table).
here order 1 and 3 matches the same itemSKu (1000001 and 1000002) and qty ( 1 and 2) and both have (2) distinct items count respectively so order 1 and 3 should be retrived at first.and when i marked order 1 and 3 as shipped (i.e chang status to 2).
and if i run query again it should retrive similar oders. now order 2 and 4 as order 2 and 4 are similar orders. (have same itemSkus (1000001, Qty (3) and distinct items count (1)).
please help thanks
You have to go trough your tables two times :)
Something like this :
SELECT DISTINCT O2.ID
FROM OrdersTable O1
INNER JOIN PurchasedProductsTable P1 ON O1.ID = P1.OrderId
INNER JOIN PurchasedProductsTable P2 ON P1.itemSku = P2.itemSku
AND P1.Qty = P2.Qty
INNER JOIN OrdersTable O2 ON O2.ID = P2.OrderId
WHERE O1.ID =
(SELECT ID FROM OrdersTable WHERE Status = 0
ORDER BY created_at ASC LIMIT 1)
AND (SELECT COUNT(*) FROM PurchasedProductsTable WHERE OrderId = O1.ID)
= (SELECT COUNT(*) FROM PurchasedProductsTable WHERE OrderId = O2.ID)
ORDER BY O2.ID ASC;
https://www.db-fiddle.com/f/65t9GgSfqMpzNVgnrJp2TR/2
You can get the earliest order via a limit and ordered by the date.
Then you can left join to get that order and any other order that at least has the same items.
Then once you have those order id's from the sub-query result, you can get the order details.
SELECT o.*
FROM
(
SELECT DISTINCT ord2.ID as OrderId
FROM
(
SELECT ID, CustomerId, Status
FROM OrdersTable
WHERE Status = 0
ORDER BY created_at
LIMIT 1
) AS ord1
JOIN PurchasedProductsTable AS pprod1
ON pprod1.OrderId = ord1.ID
LEFT JOIN OrdersTable ord2
ON ord2.CustomerId = ord1.CustomerId
AND ord2.Status = ord1.Status
LEFT JOIN PurchasedProductsTable pprod2
ON pprod2.OrderId = ord2.ID
AND pprod2.itemSku = pprod1.itemSku
AND pprod2.Qty = pprod1.Qty
GROUP BY ord1.CustomerId, ord1.ID, ord2.ID
HAVING COUNT(pprod1.itemSku) = COUNT(pprod2.itemSku)
) q
JOIN OrdersTable AS o ON o.ID = q.OrderId;
Test on RexTester here

MYSQL LEFTJOIN multiple ids same table

Im trying to get a combination of ids from a table like this:
Table activation:
user_id product_id reseller_id range_id Name
-------------------------------------------------
1 1 5 2 Oscar
1 1 5 3 Luis
2 1 5 4 Julian
Table prices (compType_id = reseller_id):
product_id compType_id price range_id
------------------------------------------------
1 5 38.60 2
1 5 48.60 3
1 5 58.60 4
Table users:
user_id name
----------------
1 lloyd
2 Mark
I want to select the activation Name and the price of prices based on the user_id.
How can i do that?
I tried something like this:
SELECT a.name
(SELECT price FROM prices WHERE product_id = 1 AND range_id =
AND compType_id = 5) AS price
FROM activation AS a
LEFT JOIN users AS u ON u.user_id = a.u_id
WHERE u.user_id = 1
The price columns have the same value in each row.
name price
Oscar 21.30
Luis 21.30
How can i change it to show the correct price?
I solved it with something like this:
SELECT a.company, a.name, a.email, a.phone, a.ruc, a.code, a.active,
a.numlic, (SELECT p.price FROM prices AS p WHERE p.product_id =
a.product_id AND p.range_id = a.range_id AND p.compType_id = c.type_id)
AS price
FROM activation AS a
LEFT JOIN users AS u ON u.user_id = a.u_id
LEFT JOIN companies AS c ON a.reseller_id = c.id
WHERE u.user_id = 1

mySQL - GROUP BY but get the most recent row

I've got a budget table:
user_id product_id budget created
-----------------------------------------------------------------
1 1 300 2011-12-01
2 1 400 2011-12-01
1 1 500 2011-12-03
2 2 400 2011-12-04
I've also got a manager_user table, joining a manager with the user
user_id manager_id product_id
------------------------------------
1 5 1
1 9 2
2 5 1
2 5 2
3 5 1
What I'd like to do is grab each of the user that's assigned to Manager #5, and also get their 'budgets'... but only the most recent one.
Right now my statement looks like this:
SELECT * FROM manager_user mu
LEFT JOIN budget b
ON b.user_id = mu.user_id AND b.product_id = mu.product_id
WHERE mu.manager_id = 5
GROUP BY mu.user_id, mu.product_id
ORDER BY b.created DESC;
The problem is it doesn't pull the most recent budget. Any suggestions? Thanks!
To accomplish your task you can do as follows:
select b1.user_id,
b1.budget
from budget b1 inner join (
select b.user_id,
b.product_id,
max(created) lastdate
from budget b
group by b.user_id, b.product_id ) q
on b1.user_id=q.user_id and
b1.product_id=q.product_id and
b1.created=q.lastdate
where b1.user_id in
(select user_id from manager_user where manager_id = 5);
I'm assuming here that your (user_id, product_id, created) combination is unique.
For what it's worth, here's the code that returned what I was looking for:
SELECT DISTINCT(b1.id),mu.user_id,mu.product_id,b1.budget,b1.created
FROM budget b1
INNER JOIN (
SELECT b.user_id, b.product_id, MAX(created) lastdate
FROM budget b
GROUP BY b.user_id, b.product_id) q
ON b1.user_id=q.user_id AND
b1.product_id=q.product_id AND
b1.created=q.lastdate
RIGHT JOIN manager_user mu
ON mu.user_id = b1.user_id AND
mu.product_id = b1.product_id
WHERE mu.manager_id = 5;
Thanks for the help Andrea!