简体   繁体   中英

how can I get a DISTINCT from mySQL but only for 1 field?

I have a row with products and I'd like to get 10 random records, but a maximum of 1 row per user_id. Right now I have this:

SELECT user_id, product_id, price, name, category, is_featured 
FROM db_products
WHERE category!=15 AND active=1 AND deleted=0 AND is_featured=1 
ORDER BY RAND() DESC LIMIT 0,12

I tried doing a SELECT DISTINCT user_id, ... but that doesn't work. The table has 100's of products and each user_id may have multiple ones, but I'd like to retrieve a maximum of 1 per user_id, but still a total of 10.

Is that possible at all without a more complex structure?

I may be missing something, but have you tried doing a GROUP BY?

SELECT user_id, product_id, price, name, category, is_featured 
FROM db_products
WHERE category!=15 AND active=1 AND deleted=0 AND is_featured=1 
GROUP BY user_id -- SPECIFY FIELD HERE
ORDER BY RAND() DESC 
LIMIT 0,12

This will group one row per user, or whichever field you desire to group by.

Try something like that with grouping in main query after random ordering in subquery:

SELECT * FROM
(SELECT user_id, product_id, price, name, category, is_featured 
FROM db_products
WHERE category!=15 AND active=1 AND deleted=0 AND is_featured=1 
ORDER BY RAND()) AS subquery
GROUP BY user_id
LIMIT 0,10

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM