1

So I'm trying to get unique results every time and I can't get it to work properly.

The user could have multiple entries in the table but I want it to only pull 2 unique entries no matter how many each user may have in the table.

This shouldn't be that difficult. Seems to be much easier in MySQL even though it's probably non standard. Anyway, this is what I have and it still pulls multiple results. It should not allow multiple mem_id's that should be unique. Right now this allows the same mem_id for both results.

SELECT media_id,mem_id FROM battle_entries WHERE active='1' AND 
mem_id!=".$mem_id." GROUP BY media_id,mem_id ORDER BY RANDOM() LIMIT 2

EDIT:

----------------------------------------------------
| btl_id | mem_id | posted | media_id | active |
----------------------------------------------------

That is what my table columns look like btl_id is a bigserial, mem_id,media_id and posted are bigint and active is smallint

There can be multiple rows where the mem_id is not unique because the user has multiple entries. I want to pull two random but unique rows by mem_id but also retrieve media_id in the select. Hope this is clearer.

4

2 回答 2

0

尝试这个:

SELECT * FROM 
    (SELECT DISTINCT ON (mem_id) mem_id, media_id 
    FROM battle_entries 
    WHERE active='1' AND mem_id!=1) s
 ORDER BY RANDOM() LIMIT 2;

sqlfiddle

于 2013-08-16T02:28:43.260 回答
0

那么你可以使用row_number:

with cte as (
    select
       *,
       row_number() over (partition by mem_id order by random()) as row_num
    from battle_entries
    where active = 1 and mem_id <> 1
)
select *
from cte
where row_num = 1
limit 2

sql 小提琴演示

于 2013-08-16T05:02:44.010 回答