你好,我有一个关于从数据库中选择随机条目的问题。我有 4 个表、产品、出价和自动出价以及用户。
Products
-------
id 20,21,22,23,24(prime_key)
price...........
etc...........
users
-------
id(prim_key)
name user1,user2,user3
etc
bids
-------
product_id
user_id
created
autobids
--------
user_id
product_id
现在多个用户可以对一个产品进行自动出价。所以对于下一个投标人,我想从自动投标表中选择一个随机用户
语言查询示例:
对于自动出价表中的每个产品,我想要一个随机用户,该用户不是最后出价者。
在产品 20 上有 user1、user2、user3 自动出价。
在产品 21 上有 user1,user2,user3 自动出价
然后我想要一个看起来像这样的结果集
20 – 用户2
21 – 用户 3
只是一个随机用户。我尝试混合 GOUP BY (product_id) 并将其设为 RAND(),但我无法从中获得正确的值。现在我得到了一个随机用户,但它的所有值都不匹配。
谁能帮我构建这个查询,我正在使用 php 和 mysql
最佳答案
解决方案的第一部分涉及识别每个产品的最新出价:这些最终会出现在临时表“latest_bid”中。
然后,我们将随机排名值分配给每个产品的每个自动出价 - 不包括每个产品的最新出价。然后,我们为每个产品选择最高排名值,然后输出具有最高排名值的自动出价的 user_id 和 product_id。
create temporary table lastbids (product_id int not null,
created datetime not null,
primary key( product_id, created ) );
insert into lastbids
select product_id, max(created)
from bids
group by product_id;
create temporary table latest_bid ( user_id int not null,
product_id int not null,
primary key( user_id, product_id) );
insert into latest_bid
select product_id, user_id
from bids b
join lastbids lb on lb.product_id = b.product_id and lb.created = b.created;
create temporary table rank ( user_id int not null,
product_id int not null,
rank float not null,
primary key( product_id, rank ));
# "ignore" duplicates - it should not matter
# left join on latest_bid to exclude latest_bid for each product
insert ignore into rank
select user_id, product_id, rand()
from autobids a
left join latest_bid lb on a.user_id = lb.user_id and a.product_id = lb.product_id
where lb.user_id is null;
create temporary table choice
as select product_id,max(rank) choice
from rank group by product_id;
select user_id, res.product_id from rank res
join choice on res.product_id = choice.product_id and res.rank = choice.choice;
关于php - 使用 group by 从数据库中获取随机记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2452081/