I’ve always been confused on how to combine multiple MySQL queries into one. I’ve been pulling my hair out trying to do the following. First, I do a query to get a result of each vendor and how many products they have:
SELECT vendor_name, COUNT(vendor_name) AS cnt FROM products GROUP BY vendor_name
Next, as I only want those vendors who have 10 or more products, I do the following PHP IF statement. I don’t know how to incorporate this in the above SELECT, so I do it via PHP. I know, it’s not the best, but when you don’t know the best way, you need to do it some way:
if ($database_row['cnt']>=10) {
Within this IF statement, I then do a query on each of the vendors that have 10 or more products:
SELECT id FROM products WHERE vendor_name="'.$database_row['vendor_name'].'"
Which gives me the id’s of each product for vendors that have at least 10 products. I know, it’s sloppy, but it generates the correct results. The issue is that I need all of this to be in one query and for the life of me I can’t figure it out. Both of these queries are in the same database, and it doesn’t seem to be that complex of a request, which is really just “show me the products of those vendors who have 10 or more products”.
Can the above be combined into one query? The current full PHP/MySQL code is as follows:
$database_result = @mysql_query('SELECT vendor_name, COUNT(vendor_name) AS cnt FROM products GROUP BY vendor_name',$database_conn);
while($database_row = @mysql_fetch_array($database_result)) {
if ($database_row['cnt']>=10) {
$database_result2 = @mysql_query('SELECT id FROM products WHERE vendor_name="'.$database_row['vendor_name'].'"',$database_conn);
// Process results
}
}
Thanks in advance!
Here’s the full single query that now works exactly as I wanted. Maybe there’s a clever way optimize the query, but it works and seems fast enough. Thanks to all!
SELECT
p3.*
FROM
(
SELECT
p1.id,
p1.department,
p1.end_date,
p1.quantity_sold,
p2.vendor_name
FROM
products p1
INNER JOIN
(
SELECT
vendor_name
FROM
products
GROUP BY
vendor_name
HAVING
COUNT(*) >= 10
) p2
ON
p1.vendor_name = p2.vendor_name
AND
p1.sold_out = 0
AND
p1.end_date > NOW()
ORDER BY
p1.end_date DESC
) AS p3
GROUP BY
p3.vendor_name
ORDER BY
p3.quantity_sold DESC
Try this