我有一个表keywords与列keywordweight 我的目标是随机选择一个keyword ,但要考虑其weight (概率)。 我找到了两种方法来解决此问题,后一种方法更优雅(并且消耗更少的资源)-但我无法运行它。 再见

表格和记录:

CREATE TABLE IF NOT EXISTS `keywords` (
  `keyword` varchar(100) COLLATE utf8_bin NOT NULL,
  `weight` int(11) NOT NULL,
  UNIQUE KEY `keywords` (`keyword`),
  KEY `rate` (`weight`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

INSERT INTO `keywords` (`keyword`, `weight`) VALUES
('google', 50),
('microsoft', 20),
('apple', 10),
('yahoo', 5),
('bing', 5),
('xing', 5),
('cool', 5);

查询1

消耗更多资源,我处理5k +记录。 资料来源是为什么使用rand()的此MySQL查询在大约三分之一的时间内没有返回结果?

SELECT *  FROM `keywords` ORDER BY -LOG(1.0 - RAND()) / weight LIMIT 1

查询2

将权重加到@weight_sum @weight_point设置@weight_point范围内的RAND()数字。 遍历所有记录,从其减去weight@weight_pos和设置@keyword到当前keywords.keyword 直到@weight_pos < 0 然后保留该keyword 来源是T-SQL中的随机加权选择

SET @keyword = 0;
SET @weight_sum = (SELECT SUM(weight) FROM keywords);
SET @rand = RAND();
SET @weight_point = ROUND(((@weight_sum - 1) * @rand + 1), 0);
SET @weight_pos = @weight_point;

SELECT
    keyword,
    weight,

    @keyword:=CASE
        WHEN @weight_pos < 0 THEN @keyword
        ELSE keyword
    END AS test,

    (@weight_pos:=(@weight_pos - weight)) AS curr_weight,
    @weight_point,
    @keyword,
    @weight_pos,
    @rand,
    @weight_sum
FROM
    keywords;

在此处查看phpmyadmin结果http://postimg.org/image/stgpd776f/

phpmyadmin

我的问题

我如何获得@keyword的值,或者test列到底包含什么? 之后添加SELECT @keyword不会更改任何内容。

===============>>#1 票数:0 已采纳

好的,我认为我的问题或多或少是一个基本的mysql问题。 通过将上面的SELECT语句封装到另一个SELECT中,我实现了所需的功能,然后针对我搜索的内容过滤了第一个结果。 对不起,打扰你。 查看查询:

SET @keyword = 0;
SET @weight_sum = (SELECT SUM(weight) FROM keywords);
SET @rand = RAND();
SET @weight_point = ROUND(((@weight_sum - 1) * @rand + 1), 0);
SET @weight_pos = @weight_point;
SELECT t.test FROM (
SELECT
    keyword,
    weight,
    @keyword:=CASE
        WHEN @weight_pos < 0 THEN @keyword
        ELSE keyword
    END AS test,
    (@weight_pos:=(@weight_pos - weight)) AS curr_weight,
    @weight_point,
    #@keyword,
    @weight_pos,
    @rand,
    @weight_sum
FROM
    keywords

) AS t

WHERE
    t.curr_weight < 0
LIMIT
    1;

  ask by spaxxUnited translate from so

未解决问题?本站智能推荐: