I have a product table:
product_id
shop_id -> id from shop table
product_pair = there is product_id, if it is paired
Then I have a shop table:
shop_id
And finally a shipping table:
shop_id -> id from shop table
country_id -> id of country
And I want to find the products which can be shipped to country_id 60
It's no problem, if it's not paired..
Like:
SELECT p.*, c.*, p.product_name AS score
FROM (`rcp_products` p)
JOIN `rcp_shipping` s ON `s`.`shop_id` = `p`.`shop_id` AND s.country_id = 60
JOIN `rcp_category` c ON `c`.`cat_id` = `p`.`cat_id`
WHERE `p`.`cat_id` = '7'
AND `p`.`product_price_eur` > 0
AND `p`.`product_mark_delete` = 0
ORDER BY `score` asc
LIMIT 10
(There are some additional WHERE's and another columns, which I think haven't got influence)
Now, I have paired products. So, in a table with products is something like this:
product_id | product_name | product_pair | shop_id
1 | Abc | 0 | 0
2 | Def | 1 | 3
3 | Ghi | 1 | 2
So, products 2 and 3 are paired to product 1.
Now, I have no idea how to get country_id for product_id = 1 in that SQL that I posted above.
Maybe my database structure is not the best :) But how can I do it better?
Thank you.
Overall, the idea that you need to use here is self-join - that's how you can find the pairs of products. After that it's just simple WHERE conditions.
The core query (the one that just finds the pairs from a specific shop) would look like this:
SELECT DISTINCT A.product_id as P1, B.product_id as P2, A.shop_id as S1, B.shop_id as S2
FROM products A, products B
WHERE (A.product_pair = B.product_id OR A.product_pair = 0) //find pair and non-paired
AND (A.product_id > B.product_id) //ensure no duplicates (e.g. A&B and B&A)
AND (A.shop_id = B.shop_id) //ensure that both can be found in the same shop
AND A.shop_id = YOUR_SHOP_ID //filter to specific shop
This should satisfy the conditions when products are sold in more than 1 shop, otherwise the query could probably become a bit shorter / easier.
Related
I have one shop table and one item table. Shop table has many item, and my problem is I want to search multiple items that available in one shop.
shop table
id | name
---------
1 | Shop 1
2 | Shop 2
Item table
id | name | shop_id
----------------------
1 | JRC | 1
2 | sukhoy | 1
3 | sukhoy | 2
When I want to find item jrc and sukhoy, so it must showing Shop 1, because both two items are ready on Shop 1.
My expected output is
Output table
id | shopName | itemName
------------------------
1 | Shop 1 | JRC
2 | Shop 1 | sukhoy
My query is
select * from shops
inner join products as produk2 on produk2.shopId = shops.id and (produk2.name like "%sukhoy%")
inner join products as produk on produk.shopId = shops.id and (produk.name like "%jrc%")
It works because it using different alias per inner join.
But what I want is, how to combine the output from that 2 join without define different alias. Or how I can combine join result into one same column ?
I think this does what you want:
select p.shop_id
from products p
group by p.shop_id
having sum(p.name like '%jrc%') > 0 and
sum(p.name like '%sukhoy%') > 0;
This returns shop ids that have both products. Of course, you can join the results to shops to get more information about the shops.
You can just use one join:
select * from shops
inner join products as produk
on produk.shopId = shops.id
and (produk.name like "%jrc%" OR produk.name like "%sukhoy%")
I have a table containing items, each item belongs to an store, e.g:
id | name | store_id | price
1 | hat | 1 | 110
2 | bag | 1 | 120
3 | coat | 2 | 130
A Store can be canonical or a duplicate. A canonical Store has canonical_id equal to null, and a duplicate Store has canonical_id equal to the ID of the canonical Store, e.g:
id | name | canonical_id
1 | NYC | null
2 | Bronx | 1
I need to group items by their Store to get the total stock value of all items at the store, e.g:
SELECT store_id, SUM(price) as `stock_value` FROM items GROUP BY store_id
This would produce 2 results, Store 1 has a stock_value of 230 and Store 2 has a stock_value of 130.
Because Store 2 is a duplicate of Store 1 the items from Store 2 should be included in the total for Store 1. The goal is for this example to provide a single result of 360.
I think the correct implementation would involve some sort of join which retrieves the Store ID from stores by using IFNULL to get either the canonical_id or id after selecting based on id from the items table, but I'm struggling to implement a solution that works.
Any pointers would be greatly appreciated, thank you.
Edit: my attempt is as follows, it appears to meet my needs, are there any caveats / issues with my approach?
SELECT SUM(price) as `stock_value`, IFNULL(stores.canonical_id, store_id) as `store`
FROM items
JOIN stores on stores.id = items.store_id
GROUP BY store
I just realize you don't wanted to keep the stock_values of the "children" or "related" stores. However the next approach take those into account too:
SELECT
s.*,
(SELECT
SUM(i.price)
FROM
items AS i
INNER JOIN
stores AS s1 ON s1.id = i.store_id
WHERE
s1.cannonical_id = s.id
OR
s.id = i.store_id) AS "stock_value"
FROM
stores AS s
Online example: DB-Fiddle
If you don't want they, you just could filter the previous query using the condition WHERE s.cannonical_id is NULL like this:
SELECT
s.*,
(SELECT
SUM(i.price)
FROM
items AS i
INNER JOIN
stores AS s1 ON s1.id = i.store_id
WHERE
s1.cannonical_id = s.id
OR
s.id = i.store_id) AS "stock_value"
FROM
stores AS s
WHERE
s.cannonical_id is NULL
But, you should note that the query you posted on the updated question will be better in performance than this approach.
Suppose I have these two tables:
|Customers | |Purchases |
---------------- -----------------
|CusID |----- |PurchaseID |
|CusName | |---<|CusID |
|CusAge | |ItemName |
|CusDateAdded | |DatePurchased |
I am needing to filter my result set by multiple ItemNames. Say I want to return all Customers who are between the ages of 18 and 24 who purchased a 'camera' AND a 'phone'. I can run the following query to obtain all records for customers between the age range:
SELECT CusID
FROM Customers AS C
JOIN Purchases AS P
ON C.CusID = P.CusID
WHERE C.CusAge BETWEEN 18 AND 24
However when it comes time to filter on the ItemName column in Purchases table how does one filter on multiple rows? Supposing it is possible without multiple queries?
SELECT C.CusID
FROM Customers AS C
JOIN Purchases AS P ON C.CusID = P.CusID
WHERE C.CusAge BETWEEN 18 AND 24
AND ItemName IN ('camera','phone')
GROUP BY C.CusID
HAVING count(distinct ItemName) = 2
Group by the customer and return only those having both items.
I believe this will answer your question: SQL FIDDLE
SELECT C.CustID,C.CustName,P.ItemName
FROM Customers AS C
JOIN Purchases AS P ON C.CustID = P.CustID
GROUP BY C.CustID,C.CustName,P.ItemName
HAVING P.ItemName IN ('camera','phone')
I have stumped all the IT people at my work with this one, so wondeirng if anyone can help.
I need to extract from an order table anyone who has only purchased a specific product type, (if they have order the product type and any other product types i dont want to know who you are)
for example the table is roughly
---------------------------------------------------------------------------------------
Order ID | item code | Name |
----------------------------------------------------------------------------------------
1 | ADA | item 1
2 | ADA | item 1
2 | GGG | item 2
3 | ADA | item 1
----------------------------------------------------------------------------------------
So i want to find all the order IDs of people who only purchased item code ADA, BUT not if they purchased over items, so the output of this query should be order ID 1 & 3 and skipping order 2 as this had a different item.
Would really appriciate it if anyone could help.
Assuming an order can't have multiple records with the same ItemCode, you could use:
SELECT *
FROM Orders
WHERE OrderID IN (
SELECT OrderID
FROM Orders
GROUP BY OrderID HAVING COUNT(*) = 1
)
AND ItemCode = 'ADA'
If an order could have multiple records with the same ItemCode then you'd have to change the SELECT * to SELECT DISTINCT * and then COUNT(*) to COUNT(DISTINCT ItemCode)
Based on your current explanation and example, the below should work. However, there are outstanding questions in the comments which may change the actual correct solution.
SELECT
O.OrderId, MAX(itemCode), MAX(Name)
FROM
Orders O
INNER JOIN
(SELECT
OrderId
FROM
Orders
WHERE
itemCode = 'ADA') ADA
ON
O.OrderId = ADA.OrderId
GROUP BY
O.OrderId
HAVING
COUNT(*) = 1
The issue:
I want to select the products which have the option_value_id of both 1 and 3. But, as you can see, it will also show the products which have only have 1 of the option_value_ids.
I tried adding AND instead of IN but that will obviously show no results.
The answer might be simple, but I just can't seem to figure it out at the moment.
Could someone help me out? Even a small hint can be appreciated.
This is called Relation Division, and here is one way to do so:
SELECT *
FROM TABLEName
WHERE Product_ID IN(SELECT Product_ID
FROM Tablename
WHERE option_value_id IN(1, 3)
GROUP BY Product_ID
HAVING COUNT(option_value_id) = 2);
SQL Fiddle Demo
This will give you:
| ID | PRODUCT_ID | OPTION_VALUE_ID |
-------------------------------------
| 1 | 1 | 1 |
| 3 | 1 | 3 |
| 13 | 2 | 3 |
| 14 | 2 | 1 |
This is example of looking at things as a set. I think the best approach is to use SQL's aggregation, particularly the having clause. In MySQL syntax, this looks like:
select pa.product_id
from Product_Attributes pa
group by pa.product_id
having max(pa.option_value_id = 1) = 1 and
max(pa.option_value_id = 3) = 1
Try this:
SELECT *
FROM products_attributes
WHERE option_value_id IN (1, 3)
GROUP BY product_id
HAVING COUNT(*) = 2
This is a common problem, called Relational Division, there is even a tag in SO for it: sql-match-all
Usually, there is a unique constraint on the (product_id, option_value_id), so one solution is to use 2 joins (N joins if you want to check for N attributes):
SELECT p.* -- whatever columns you need
FROM product AS p -- from the `product` table
JOIN products_attributes AS pa1
ON pa1.option_value_id = 1
AND pa1.product_id = p.product_id
JOIN products_attributes AS pa2
ON pa2.option_value_id = 3
AND pa2.product_id = p.product_id ;
There is a similar question, with more than 10 different ways to achieve the same result (and benchmarks for Postgres): How to filter SQL results in a has-many-through relation