pull data from multiple tables in one query and matching data together - php

OK I have two sql tables I need to query from which are product and product_to_category
product looks like
product_to_category looks like
I am trying to query both the tables so that I can select all that are in a certain category number, which is in product_to_category, but also select all that have a status of 1, which determines if they are active or not. I am trying to do this in a single query, and so far my query looks like what is below, problem is that I am not sure how to match the product_id's together to work how I would like. Can someone give me an idea of how to do this?
mysql_query("SELECT * FROM product,product_to_category WHERE product.status = 1 AND product_to_category.category_id = 35 ORDER BY product.sort_order ASC")

Try:
SELECT * FROM product
INNER JOIN product_to_category ON (product.product_id = product_to_category.product_id)
WHERE
product_to_category.category_id = 35
AND
product.status = 1

you should use a JOIN
SELECT *
FROM product p
INNER JOIN product_to_category pc
ON p.productid = pc.productid
WHERE p.status = 1
AND pc.category_id = 35
ORDER BY p.sort_order ASC
since you are not familiar with joins, I suggest reading the following:
A Visual Explanation of SQL Joins:
http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html

Try this:
mysql_query("SELECT * FROM product JOIN product_to_category ON (product.product_id = product_to_category.product_id) WHERE product.status = 1 AND product_to_category.category_id = 35 ORDER BY product.sort_order ASC")

Try following query. It is easier to comprehend
SELECT * FROM
product a
JOIN product_to_category b ON a.product_id = b.product_id
WHERE
a.stock_status_id = 1
AND b.category_id = 35;

mysql_query("SELECT * FROM product p LEFT JOIN product_to_category pc ON (p.id = pc.product_id) WHERE p.status = 1 AND pc.category_id = 35 ORDER BY p.sort_order ASC");
This should do the trick. Make sure you look in to JOINS and their different types

Related

Mysql function count() counts rows individually

I have the following query, where i want to get the total number of rows but this seems to count each individually here is the query and the result
SELECT
COUNT(pc.product_id)
FROM
products as p
INNER JOIN product_categories as pc
ON p.product_id = pc.product_id AND pc.subcategory_id IN (77)
GROUP BY pc.product_id
HAVING COUNT(pc.subcategory_id) = 1
Result is :
COUNT(pc.product_id)
1
1
1
...but it should be
COUNT(pc.product_id)
3
UPDATE
the above query should count the number of products that are get by this query
SELECT
*
FROM
products as p
INNER JOIN product_categories as pc
ON p.product_id = pc.product_id AND pc.subcategory_id IN ($sb_2)
GROUP BY pc.product_id
HAVING COUNT(DISTINCT pc.subcategory_id) = $sb_count
$sb_2 = 77,76;
$sb_count = how many values are in $sb_2;
77 and 76 are different subcategories ids but are common for some products
If you know another way to count this or to make another query...
SELECT
COUNT(pc.product_id)
FROM
products as p
INNER JOIN product_categories as pc
ON p.product_id = pc.product_id AND pc.subcategory_id IN (77)
HAVING COUNT(pc.subcategory_id) = 1
Removing the group by should do the trick.
I manage to count rows by the following query.
"SELECT COUNT(*) as count FROM (SELECT
*
FROM
product_categories WHERE subcategory_id IN (77,76)
GROUP BY product_id
HAVING COUNT(DISTINCT subcategory_id) = 2) as subc";
}

SQL JOIN - Need to return one product id but all variations of it (e.g. Size, colour)

I have several tables I'm joining to display my product details from a stock table. Therefore, one product ID can have many entries in the stock table due to multiple colours and sizes.
Table 1: tblStock
stockID
productID
sizeID
colourID
qty
Table 2: tblColour
colourID
colourName
colourHEX
Table 3: tblSize
sizeID
sizeName
My query:
SELECT p.productID, c.colourName, c.colourHEX, sz.sizeName, s.qty
FROM tblProducts p
INNER JOIN tblStock s ON p.productID = s.productID
INNER JOIN tblColour c ON s.colourID = c.colourID
INNER JOIN tblSize sz ON s.sizeID = sz.sizeID
WHERE p.productID = '$id'
is returning:
productID colourName colourHEX sizeName qty
4 Burgundy #621b40 Small 10
4 Burgundy #621b40 Medium 15
4 Burgundy #621b40 Large 20
4 Pink #ba0046 Large 20
Is there any way that I can only return the product ID once but keep all it's variations?
If not, how would I echo this product to the page as I don't want it to appear 4 times. Just appear once with the various options available detailed.
You can use the group_concat function
SELECT p.productID, group_concat(distinct c.colourName), group_concat(distinct c.colourHEX), group_concat(distinct sz.sizeName), sum(s.qty)
FROM tblProducts p
INNER JOIN tblStock s ON p.productID = s.productID
INNER JOIN tblColour c ON s.colourID = c.colourID
INNER JOIN tblSize sz ON s.sizeID = sz.sizeID
WHERE p.productID = '$id'
group by p.productID ;// group by required only if you product id clause is removed
I'm not used to PHP but your problem is very simple.
All you need is a separate variable inside a loop like this:
sql="SELECT p.productID, c.colourName, c.colourHEX, sz.sizeName, s.qty"
sql=sql+"FROM tblProducts p"
sql=sql+"INNER JOIN tblStock s ON p.productID = s.productID"
sql=sql+"INNER JOIN tblColour c ON s.colourID = c.colourID"
sql=sql+"INNER JOIN tblSize sz ON s.sizeID = sz.sizeID"
sql=sql+"WHERE p.productID = '$id'"
Set rs = RecordSetForStoringSQLQueryResult -- Replace with appropriate code in PHP
rs.Open (connectionName, sql)
$prevProductID = Null; -- Or some other number
while not rs.EndOfFile
$currentId = rs("productID")
if ($currentId != $lastId) {
-- New ID found, display it.
echo($currentId);
$prevProductID = $currentId
} else {
-- Code for logic when the current product ID is same as previous product ID
-- You will not assign anything to $prevProductID in this section.
}
rs.MoveToNextRecord
end while
Kindly consider that I am not a PHP guy, but I have done similar things in classic ASP. The code above is just for illustration purposes and it is not directly usable. You will need to tweak it as per your plan.

MySQL Count Query not working but its display records list

I try to use this Query to get Number of Records bu tits not display count in phpMyAdmin
And also give me the wrong result when i try to remove LIMIT from Query..
SELECT COUNT(*) as `num` FROM fm_detail
LEFT JOIN lang ON lang.l_id = fm_detail.language_id
LEFT JOIN country ON country.c_id = fm_detail.country_id
LEFT JOIN users ON users.usr_id = fm_detail.submitter_id
LEFT JOIN category ON category.cat_id = fm_detail.category_id
INNER JOIN city ON fm_detail.city_fm = city.city_id
where 1=1 AND fm_detail.category_id = '1' LIMIT 10 , 5
This query did not give me any Record Count..
But when i use..
SELECT * FROM fm_detail
LEFT JOIN lang ON lang.l_id = fm_detail.language_id
LEFT JOIN country ON country.c_id = fm_detail.country_id
LEFT JOIN users ON users.usr_id = fm_detail.submitter_id
LEFT JOIN category ON category.cat_id = fm_detail.category_id
INNER JOIN city ON fm_detail.city_fm = city.city_id
where 1=1 AND fm_detail.category_id = '1' LIMIT 10 , 5
This give me the Records list in PHPMYADMIN..
I don't know how to use this query to fix my problem.
Please help me asap..
Thanks,
Because you use COUNT function (which in your case returns one row) and LIMIT clause that starts from 10 record. So, you do not get any records at all.
About the LIMIT... maybe select distinct will help to get the right count. Joins sometimes create duplicated rows.

How to return the highest scoring image for a given product?

I have two tables, products and product_images. I have a third table 'product_categorys' too but I'm not sure how relevant this is for the question).
In the product Images table I have a column named score as an int as well as a product_id column. I would like to select a row or rows from the product table and have the highest scoring image return also. So far I have this:
SELECT `products`.*, `product_categorys`.`categoryName`, `product_categorys`.`categoryDescription`, `product_images`.`thumbName`
FROM (`products`)
INNER JOIN `product_categorys` ON `products`.`categoryID` = `product_categorys`.`pid`
left JOIN `product_images` ON `products`.`pid` = `product_images`.`productID`
WHERE `products`.`vendorID` = '14'
AND `products`.`deleted` = 0
GROUP BY `products`.`pid`
ORDER BY `title` asc
LIMIT 10
Which returns a product image but not the highest scoring one, I'm not sure how to go about modifying this query (This has been generated by codeigniter) to give me what I need.
What needs to be changed/added to allow the query to return the highest scoring image please ?
I don't know it it works, but give it a try:
SELECT p.*,
pc.categoryName, pc.categoryDescription,
pim.thumbName, pim.score
FROM products p INNER JOIN product_categorys pc
ON p.categoryID = pc.pid
LEFT JOIN product_images pim
ON p.pid = pim.productID
WHERE p.vendorID = '14'
AND p.deleted = 0
AND (pim.score =
(SELECT MAX(score) FROM product_images pim2
WHERE p.pid = pim2.productID)
OR pim.score IS NULL)
GROUP BY p.pid
ORDER BY title ASC
LIMIT 10

mysql query - only select where id = id from another table and a field in that table = a value

my title may not explain what I am looking for, this is my current query for pulling in products for a shop:
mysql_query("SELECT * FROM Items
WHERE ((Items.menu_id='$menu_id' AND Items.status='1')
$colour_sql)
$order_sql
LIMIT $lim_from,$limit_per_page");
The part where it says $colour_sql I want to have somthing that says:
AND (Items.id=colour.product_id AND colour.colour='pink')
So it only show products that are pink, with the colours being in a seperate table. I have searched for answers, but I can't seem to find one explaining my situation, maybe its because I don't know exactly what i'm, looking for, any help is appreciated thanks.
If you want to join with table colour you need to do either a join or a subselect.
Join
$menu_id = mysql_real_escape_string($menu_id);
mysql_query = "SELECT i.*
FROM items i
INNER JOIN colour c ON (c.product_id = i.id)
WHERE i.menu_id = '$menu_id'
AND i.status = '1'
AND c.colour = 'pink'
ORDER BY .....
LIMIT {intval($limit_per_page)} OFFSET {intval($lim_from)} ";
Subselect
$menu_id = mysql_real_escape_string($menu_id);
mysql_query = "SELECT i.*
FROM items i
WHERE i.menu_id = '$menu_id'
AND i.status = '1'
AND i.id IN (SELECT c.product_id FROM colour c WHERE c.colour = 'pink')
ORDER BY .....
LIMIT {intval($limit_per_page)} OFFSET {intval($lim_from)} ";
maybe an inner join?
[...]
FROM Items
INNER JOIN colour
ON colour.id = Items.colour_id
WHERE [blablabla]
AND colour.colour = 'pink'
You need to add the colour table to your query:
FROM Items,colour
or
From Items INNER JOIN colour ON Items.id = colour.product_id
But I observed that you have the product_id in your colour table. Why don't you do the reverse in the Items table you add the colour id.

Categories