Jump to content

how can i do this?? random and joins?


acidglitter

Recommended Posts

where i'm working, we have three tables... one for products, one for categories and one for the groups the categories fall under. if a product is new, in the ifnew field it will have a '1'. there will probably always be at least 10 new products in each category group. what i want to do is randomly show three new products for each category group.

 

 

this is what i have so far...

 

SELECT p.name, p.category_id, c.group_id, g.name AS 'group'
FROM products AS p
INNER JOIN categories AS c ON
	p.category_id = c.category_id
INNER JOIN categorygroups AS g ON
	c.group_id = g.group_id
WHERE p.ifnew='1'
ORDER BY c.group_id ASC

 

its showing EVERY new product in each group.... how can i change it to only randomly show three new products from each group?

Link to comment
Share on other sites

thanks. i'm still in the middle of reading that, but do you think it would just be better to do something like

 

$query=mysql_query("select name, group_id from category groups order by group_id asc");
while($group=mysql_fetch_array($query)){
$products=mysql_query("select p.name from products as p
	inner join categories as c on p.category_id = c.category_id
	where c.group_id='{$group['group_id']}'");

while($product=mysql_fetch_array($products)){
	// display products
}
}

 

 

that would be 4 queries instead of one though

Link to comment
Share on other sites

... but basically, you need to generate a table of the 3 new products per group first, and then join it back.

 

one of the examples from that page is

(select * from fruits where type = 'apple' order by price limit 2)

union all

(select * from fruits where type = 'orange' order by price limit 2)

union all

(select * from fruits where type = 'pear' order by price limit 2)

union all

(select * from fruits where type = 'cherry' order by price limit 2)

 

is that what you meant? or did you mean actually making a separate table for the new products?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.