0

我想构建一个查询来随机显示来自 ITEM 表的用户的项目,但根据项目类别在 PREFERENCE 表中存在的次数(更大的偏差)。类别必须自动添加到查询中。

ITEM TABLE
Itemname   Category Id
'item1', '20081'
'item2 ', '15032'
'items3', '20081'
'item4', '20081'

PREFERENCE TABLE
Userid, Categoryname, Categoryid
'79', 'Everything Else', '15032'
'146', 'Antiques', '20081'
'79', 'Antiques', '20081'
'79', 'Antiques', '20081'
'79', 'Antiques', '20081'

在简单的意义上它是这样的

SELECT * FROM `ex`.`item` where category_id=20081 or category_id=79 /*there rest to be added automatically and also with the bias depending on the count in preference  */order by rand();
4

2 回答 2

1
SELECT  *,
        (
        SELECT  COUNT(*)
        FROM    preference
        WHERE   (p.userid, p.categoryid) = (79, i.categoryid)
        ) AS pref
FROM    item i
LEFT JOIN
        preference p
ON      (p.userid, p.categoryid) = (79, i.categoryid)
WHERE   category_id IN (20081, 79)
ORDER BY
        RAND() + 1 - POW(0.7, pref)
LIMIT 25

对于无偏项,排序值将在 [0, 1) 内均匀随机,对于 1 个偏好,在 [0.3, 1.3) 内,对于 2 个偏好,在 [0.51, 1.51) 内等。

您可能想提出一个更复杂的偏差公式

于 2013-09-20T18:05:51.377 回答
1
SELECT i.*
FROM item i
JOIN (SELECT Categoryid, COUNT(*) cat_count
      FROM preference
      WHERE Categoryid IN (20081, 79)
      GROUP BY Categoryid) p
ON i.Categoryid = p.Categoryid
ORDER BY cat_count*RAND() DESC
于 2013-09-20T18:06:00.940 回答