如何构建具有偏差的mysql查询与多次出现的项目

时间:2013-09-20 17:58:57

标签: php mysql sql

我想构建一个查询,以便随机地从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();

2 个答案:

答案 0 :(得分: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]等。

您可能想要提出更复杂的偏见公式

答案 1 :(得分: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