I have SQL to count products with specific properties. I am using it in the products filter. SQL is very long, but here is the primary part:
SELECT COUNT(products.id) as products_count, property_items.description, property_items.id as id
FROM property_items
INNER JOIN product_properties ON property_items.id = product_properties.property_item_id
INNER JOIN products ON product_properties.product_id
INNER JOIN product_properties pp ON products.id = pp.product_id AND (pp.property_item_id IN ($ids))
GROUP BY property_items.id
HAVING COUNT(pp.id) >= $countIds
This works perfectly when I have only the one element in $ids, but when i choose one more, the result is bad. It looks like the sql returns count of all products with any property from $ids, but I need to count only products that contains all properties.
First get all available properties. On each property join products that contains this property and go back to all properties of this product to check, if product contains already checked properties too. Or it is bad idea? I need to keep primary table (FROM table) as property_items.
I need to get result in this format:
=============================
id|description|products_count
=============================
1 |lorem ipsum|10
-----------------------------
2 |dolore sit |2
Thanks for any idea.
Try to use SELECT COUNT (DISTINCT products.id) as cnt
You can get the product ids that have all the properties by doing:
SELECT pp.property_id
FROM property_items pi INNER JOIN
product_properties pp
ON pi.id = pp.property_item_id INNER JOIN
products p
ON pp.product_id = p.id
WHERE pp.property_item_id IN ($ids)
GROUP BY pp.property_id
HAVING COUNT(DISTINCT pp.property_item_id) = $countIds -- has all of them
Note that I rationalized the joins. I think your simplification of the query wasn't quite right. I also added table aliases, so the query is easier to write and to read.
If you want the count of such products, use a subquery:
SELECT COUNT(*)
FROM (SELECT pp.property_id
FROM property_items pi INNER JOIN
product_properties pp
ON pi.id = pp.property_item_id INNER JOIN
products p
ON pp.product_id = p.id
WHERE find_in_set(pp.property_item_id, $ids)
GROUP BY pp.property_id
HAVING COUNT(DISTINCT pp.property_item_id) = $countIds -- has all of them
) ;
Your problem is probably because of this line:
WHERE pp.property_item_id IN ($ids)
If you are passing $ids as a comma-separated string, then your query will not work. Note the replacement above.
Related
Running the following SELECT query gives unexpectedly two times the same record while there is only 1 product in the database. The are however multiple subcategories linked to the same category, but I still don't understand why this would give two results.
The ERD:
The full contents of the DB:
SELECT p.id AS productId, p.name AS productName FROM product p
INNER JOIN product_base AS pb ON pb.id = p.product_base_id
INNER JOIN product_category AS pc ON pc.id = pb.product_category_id
INNER JOIN product_subcategory AS psc ON psc.product_category_id = pc.id;
Returns:
Why is this product returned two times?
Appending WHERE psc.id = 2 will still give one product as a result, while the intention is that this product should only be found when psc.id = 1.
What am I missing here? Is there something wrong with the structure? How would I get all products that have a certain subcategory?
Would I need to store product_category_id and product_subcategory_id directly in product as well?
#barmar made me realize I am simply missing a direct FK from product to product_subcategory. Otherwise there is of course a missing link between the product and subcategory.
DISTINCT will filter out the duplicates.
SELECT DISTINCT p.id AS productId, p.name AS productName
FROM product p
INNER JOIN product_base AS pb ON pb.id = p.product_base_id
INNER JOIN product_category AS pc ON pc.id = pb.product_category_id
INNER JOIN product_subcategory AS psc ON psc.product_category_id = pc.id;
I have the following tables in my database.I only listed the important columns which can be used for joining.
I need to get the following output
Currently I'm using two seperate queries for each COUNT value
For assigned licenses
select
products.id,products.name,COUNT(assigned_licenses.id)
from
deployment_users
inner join
assigned_licenses
on
deployment_users.id = assigned_licenses.deployment_user_id
inner join
products
on
assigned_licenses.id = products.id
and
deployment_users.customer_id = 10
group by
assigned_licenses.id
;
For total licenses
select
products.id,products.name,COUNT(total_licenses.id)
from
customers
inner join
total_licenses
on
customers.iccode = licenses.iccode
inner join
products
on
total_licenses.id = products.id
and
customers.id = 10
group by
total_licenses.id
;
Since there are more than a 1,000 products that need to be listed,I want to combine them into a single query.How can I do that?
Your specification leaves some room for interpretation (e.g. can a user have assigned licenses without total licenses? if yes my query will fail.) but I would go with this.
SELECT
products.id,
products.name,
Count(Distinct total_licenses.id) As CountTotalLicenses,
Count(Distinct assigned_liceses.deployment_users_id) As CountAssignedLicenses
FROM products
LEFT JOIN total_licenses ON total_licenses.products_id = products.id
LEFT JOIN customers ON customers.iccode = total_licenses.customers_iccode
LEFT JOIN assigned_licenses ON assigned_liceses.total_licenses_id = total_licenses.id
WHERE
customers.id = 10
GROUP BY
products.id,
products.name
For the future it would be awesome if you could paste code as code and not as an image. People cannot simple copy paste snippets of your code and have to type everything again...
Try joining Both of your query
SELECT * FROM (
(First Query) as assigned_licn
INNER JOIN
(Second Query) as total_licn
USING (id)
);
SQL newbie here.
So we have 3 tables:
categories(cat_id,name);
products(prod_id,name);
relationships(prod_id,cat_id);
It is a one-to-many relationship.
So, given a category name say "Books". How do I find all the products that come under books?
As an example,
categories(1,Books);
categories(2,Phones);
products(302,Sherlock Holmes);
relationships(302,1);
You need to JOIN the three tables.
SELECT p.*
FROM relationships r
INNER JOIN products p
ON p.prod_id = r.prod_id
INNER JOIN categories c
ON c.cat_d = r.cat_id
WHERE c.name = 'Books'
You have to join tables on related columns and specify WHERE clause to select all records where category name = 'Books'
SELECT p.*
FROM categories c
JOIN relationships r ON c.cat_id = r.cat_id
JOIN products p ON r.prod_id = p.prod_id
WHERE c.name = 'Books' -- or specify parameter like #Books
In SQL you often join related tables and beginners tend to join, whatever the situation. I would not recommend this. In your case you want to select products. If you only want to show products data, select from products only. You want to select products that are in the category 'Books' (or for which exists an entry in category 'Books'). Hence use an IN or EXISTS clause in order to find them:
select * from products
where prod_id in
(
select prod_id
from relationships
where cat_id = (select cat_id from categories where name = 'Books')
);
Thus you get a well structured query that tells the reader easily how the tables are related and what data you are actually interested in. Later, with different tables and data to select, this may keep you from duplicate result rows that you must get rid of by using DISTINCT or from getting wrong aggregates (sums, counts, etc.), because of mistakenly considering records multifold.
try this:
select p.Prod_id,p.name
from products p inner join relationships r on
p.prod_id = r.prod_id
where r.cat_id = (select cat_id from categories where name = 'books')
or
select p.Prod_id,p.name
from products p inner join relationships r on
p.prod_id = r.prod_id inner join categories c on c.cat_id = r.cat_id
where c.name = 'books'
I have a query which selects products from a table. A product can have multiple prices (think of various prices) and a default price.
Naturally, this is a one-to-many relation. I need to select the products which have a given price, or the default price - which means mutual exclusion. I know this can be done through separate queries and a WHERE (not) IN clauses or a union statement, but I'm convinced a more optimal way must be possible. My query currently looks like this:
SELECT products.*, products_prices.price
FROM products RIGHT JOIN
products_prices ON (products.id = products_prices.productId)
WHERE products_prices.businessId = ?
OR products_prices.businessId IS NULL // this needs to become mutual.
EDIT: I ended up using this query, which is a slightly modified version of Gordon Linoff's:
SELECT distinct p.*, coalesce(pp.price, defpp.price)
FROM products p LEFT JOIN
products_prices pp
ON p.id = pp.productId and pp.businessId = ? left join
products_prices defpp
on p.id = defpp.productId and defpp.businessId is NULL
If I understand your question correctly, the products table would have the default price and the product_prices table would have any other price.
You want to know where the default price is being used, meaning that there are no other prices. For this, use a left outer join:
SELECT p.*, coalesce(pp.price, p.default_price)
FROM products p LEFT OUTER JOIN
products_prices pp
ON p.id = pp.productId
WHERE pp.price = GIVENPRICE or pp.price is null
Based on your comment, you are storing the default prices in records with the business id being NULL. In this case, I would do two joins to the prices table:
SELECT p.*, coalesce(pp.price, defpp.price)
FROM products p LEFT OUTER JOIN
products_prices pp
ON p.id = pp.productId and pp.price = GIVENPRICE left outer join
products_prices defpp
on p.id = defpp.productId and defpp.businessId is NULL
The first join gets the price matching the given price. The second gets the default price. The first result is used, if present, otherwise the second is used.
I am attempting to do a tag system for selecting products from a database. I have read that the best way to achieve this is via a many-to-many relationship as using LIKE '%tag%' is going to get slow when there are a lot of records. I have also read this question where to match on multiple tags you have to do a join for each tag being requested.
I have 3 tables: shop_products, shop_categories and shop_products_categories. And I need to, for example, be able to find products that have both the tag "flowers" and "romance".
SELECT p.sku, p.name, p.path FROM shop_products p
LEFT JOIN shop_products_categories pc1 ON p.sku = pc1.product_sku
LEFT JOIN shop_categories c1 ON pc1.category_id = c1.id
LEFT JOIN shop_products_categories pc2 ON p.sku = pc2.product_sku
LEFT JOIN shop_categories c2 ON pc2.category_id = c2.id
WHERE c1.path = 'flowers' AND c2.path = 'romance'
This is the demo query I'm currently building to check it works before coding the relevant PHP for it and it works. But is this really the best way to do this? I find it hard to believe there isn't a better way to do this than to do a join for each tag searched.
Thanks for any advice. :)
No need to do multiple joins. If you need to match all tags, you can use an IN clause with a subquery like this:
select p.sku, p.name, p.path
from shop_products p
where p.sku in (
select pc.product_sku
from shop_products_categories pc
inner join shop_categories c on pc.category_id = c.id
where c.path in ('flowers', 'romance')
group by pc.product_sku
having count(distinct c.path) = 2
)
Note that you will need to adjust the number 2 to be the number of unique tags you are matching on. Beware in case this is user-entered data and they enter the same tag twice.
SELECT
p.sku, p.name, p.path
FROM
shop_products p
INNER JOIN
(
SELECT A.sku FROM
(
SELECT product_sku sku FROM shop_products_categories
WHERE category_id=(SELECT id FROM shop_categories WHERE path='flowers')
) A
INNER JOIN
(
SELECT product_sku sku FROM shop_products_categories
WHERE category_id=(SELECT id FROM shop_categories WHERE path='romance')
) B
USING (sku)
) flowers_and romance
USING (sku)
;
Make sure you have these indexes:
ALTER TABLE shop_categories ADD INDEX (path,id);
ALTER TABLE shop_categories ADD UNIQUE INDEX (path);
ALTER TABLE shop_products_categories ADD INDEX (product_sku,category_id);