Pull data from 3 tables - mysql

I have 3 tables as follows :
Table 1: Product
id_product [Primary Key],added_time.
Table 2: Category
id_category [Primary Key],Category_name.
Table 3: product_category
id_category,id_product [Both Foreign Keys]
I want to pull Data as
Category_name,No Of Products in this Category,Last time when product was added to Category(Latest product added_time).

You could use this SQL:
SELECT Category.Category_name,
Count(DISTINCT Product.id_product) AS num_products,
Max(Product.added_time) last_added_time
FROM Category
LEFT JOIN product_category
ON product_category.id_category = Category.id_category
LEFT JOIN Product
ON Product.id_product = product_category.id_product
GROUP BY Category.Category_name;
Note that by using LEFT JOIN you will be certain to list all categories even those for which no products exist. If you don't want those, replace both LEFT keywords with INNER.
Note also that in standard SQL you need to GROUP BY any columns you mention in the SELECT list, unless they are aggregated, like with MAX or COUNT.

SELECT C.`Category_name`,
(SUM(IF(P.`id_product`IS NULL,0,1))) AS No_of_Products,
MAX(P.`added_time`) AS Latest_time
FROM
Category C
LEFT JOIN
product_category P_C ON C.`id_category` = P_C.`id_category`
LEFT JOIN
Product P ON P.`id_product` = P_C.`id_product`
GROUP BY C.`id_category`
Hope this helps.

Related

How to get Data from three tables in one query where table 2 contains foreign keys from table 1 and 3

I want to get all the suppliers for one product with product details for which I am using following tables.
I have one Table products with columns
id(pk)
name
type
second table product_supplier with columns
psid(pk)
pid(fk from products)
sid(fk from supplier)
third table supplier with columns
id(pk)
firstname
lastname
I want to get data from these three tables in one mysql query.
Is this what you are looking for?
select p.*, s.*
from products p
inner join product_supplier ps on ps.pid = p.id
inner join supplier s on s.id = ps.sid
order by p.id, s.id
This will return each product along with all the associated suppliers.

SQL JOIN: Select Records from Another Table With Matching IDs

I am having trouble building a correct SQL JOIN statement to select some records from another table.
--Table Product:
ID
Name
CatID1
CatID2
and
--Table Category:
CatID
CategoryName
Product.CatID1, Product.CatID2 are referenced to Category.CatID
So I really want to select Product fields and replace Product.CatID1, Product.CatID2 with Category.CategoryName (for Product.CatID1) and Category.CategoryName (for Product.CatID2).
This obviously does not work but explains what I need:
SELECT Product.ID, Product.Name,
Category.CategoryName as Product.CatID1,
Category.CategoryName as Product.CatID2
from product, categories;
All you need is a double LEFT JOIN to categories table:
SELECT p.ID, p.Name,
c1.CategoryName as CatID1,
c2.CategoryName as CatID2
from product AS p
LEFT JOIN categories AS c1 ON p.CatID1 = c1.CatID
LEFT JOIN categories AS c2 ON p.CatID2 = c2.CatID
If there is no match for either CatID1 or CatID2, the corresponding field in the SELECT clause is going to be NULL.
SELECT Product.ID,
Product.Name,
C1.CategoryName as Product.CatID1,
C2.CategoryName as Product.CatID2
FROM Product JOIN Category C1 ON C1.CatID = CatID1
JOIN Category C2 ON C2.CatID = CatID2 ;
Use the category table twice.
What if you decide, in the future, that a product can be in 3 categories? Really, you should have a joining table for these and remove the repeating info from Product.

How to get names of relevant ID's from 2 different tables and display them

I have 3 tables, First one has the product ID and Name, Second one has Supplier ID and name, In the 3rd one i have product ID and Supplier ID. While displaying, i want to replace the product ID and supplier ID in the 3rd table with product name and supplier name from the 1st and 2nd table respectively.
Please let me know the query for executing it.
Reference: http://dev.mysql.com/doc/refman/5.7/en/join.html
SELECT * FROM table1
INNER JOIN table2
ON table1.id=table2.id
INNER JOIN table3
ON table2.id=table3.id;
If your tables are named products_master, stockists_master, and stockist_product_offer, then you can join the tables and select any of the six columns that you want.
SELECT product_master.name, stockists_master.name
FROM products_master
INNER JOIN stockist_product_offer
ON product_master.id = stockist_product_offer.product_id
INNER JOIN stockists_master
ON stockist_product_offer.stockist_id = stockist.id;
you have to join the tables on IDs so the query is :
let s say that :
* first table : product
* second table : supplier
* third table : match
SELECT P.PRODUCTNAME
S.SUPPLIERNAME
FROM
PRODUCT P
INNER JOIN
MATCH M
ON P.PRODUCTID = M.PRODUCTID
INNER JOIN
SUPPLIER S
ON S.SUPPLIERID = M.SUPPLIERID
ORDER BY 1
;

SQL: Get Products from a category but also must be in another set of categories

I am currently stuck in a situation. The scenario is this. I have products who may be associated with multiple categories. The data structure is shown below:
Products Table:
product_id name
1 Lemon
2 Kiwis
3 Cheese
Product to Categories Table
product_id category_id
1 1
1 2
1 3
2 1
2 3
3 2
3 4
Category Table (not required in query however adding it here to help visualize what is happening)
category_id name
1 Fruit
2 Yellow
3 Round
4 Dairy
What I'm struggling with here is that originally I want to get all products that are in the fruit category (category id 1) but I also want to check if a fruit is yellow. Keep in mind that yellow will not be the only filter, sometimes I will want to return yellow and orange fruit, however since cheese is yellow I can't return it since it isn't a fruit. However to make things a bit easier I always know that I am going to look in the fruit category as a base.
The database structure can not change as its an opencart database structure.
Here are my attempts:
SELECT GROUP_CONCAT(DISTINCT p2c2.category_id SEPARATOR ',') as categories
FROM oc_product_to_category p2c
LEFT JOIN oc_product p ON (p.product_id = p2c.product_id)
LEFT JOIN oc_product_to_category p2c2 ON (p.product_id = p2c2.product_id)
WHERE p2c.category_id IN ('1','2')
This kind of works except for that fact that it will return Cheese.
Notes: I use Group Concat because at the end of all of this my goal is to return not so much the products that match these categories but based on the filters I want to return another list of categories from the products that match this criteria. So:
Scenario:
Get Products that match category criteria
Return categories of those products.
Any assistance will be greatly appreciated.
This type of problem is called relational division.
There are two common solutions:
First solution strings together the matching categories and compares to a fixed string:
SELECT p2c.product_id
FROM oc_product_to_category p2c
GROUP BY p2c.product_id
HAVING GROUP_CONCAT(p2c.category_id SEPARATOR ',' ORDER BY p2c.category_id) = '1,2'
Second solution does a JOIN for each required value:
SELECT p.product_id
FROM oc_product p
INNER JOIN oc_product_to_category p2c1
ON (p.product_id = p2c1.product_id AND p2c1.category_id = 1)
INNER JOIN oc_product_to_category p2c2
ON (p.product_id = p2c2.product_id AND p2c2.category_id = 2)
I cover these solutions in my presentation SQL Query Patterns, Optimized. I found in my tests that the join solution is much better for performance.
#Tom's suggestion is right, here's what that would look like in a complete query:
SELECT p.product_id, GROUP_CONCAT(p2c3.category_id SEPARATOR ',') AS categories
FROM oc_product p
INNER JOIN oc_product_to_category p2c1
ON (p.product_id = p2c1.product_id AND p2c1.category_id = 1)
INNER JOIN oc_product_to_category p2c2
ON (p.product_id = p2c2.product_id AND p2c2.category_id = 2)
INNER JOIN oc_product_to_category p2c3
ON (p.product_id = p2c3.product_id)
GROUP BY p.product_id;
The DISTINCT that #Tom suggests shouldn't be necessary, because your p2c table should have a UNIQUE constraint over (product_id, category_id).

selecting from multiple tables with counter

I have two tables one holds a category with column catID,catName and the other has the catID as a foreign key, now i want to select all the total items on the second table based on their catID.
E.g. What is the total number of individual element if their category is 1,2,3,4 etc. Pls code hints will help thanks.
SELECT
c.cat_id
,count(*) as occurence
FROM category c
INNER JOIN table2 t ON (c.cat_id = t.cat_id)
GROUP BY c.cat_id
If you want the categories with occurence = 0 then do:
SELECT
c.cat_id
,count(t.cat_id) as occurence
FROM category c
LEFT JOIN table2 t ON (c.cat_id = t.cat_id)
GROUP BY c.cat_id
Links:
http://dev.mysql.com/doc/refman/5.5/en/group-by-functions.html
http://www.1keydata.com/sql/sqlgroupby.html
SELECT catName, COUNT(table2.catId) FROM table1,table2
WHERE table1.catId=table2.catId
GROUP BY catName