mysql - 使用 MySQL 将包含相同索引的其他表中的值相乘

标签 mysql sql

sourceindex | source | target | prob
    1       | apple  |   dog  | 2/(2+2+1)
    2       | dog    |   cat  | 2/(2+2+1)
    3       | door   |   cat  | 1/(2+2+1)
    2       | dog    |   apple| 2/(2+2+1)  
    4       | cat    |   dog  | 2/(2+2+1)  -----step 1  table1

sourceindex | source | target | prob
    1       | apple  |   dog  | 2/(2+2+1)
    2       | dog    |   cat  | 4/(2+2+1)
    3       | door   |   cat  | 1/(2+2+1)  
    4       | cat    |   dog  | 2/(2+2+1)  -----step 2  sum the prob group by sourceindex
                                                        and output to new table 



---------------------------------------------

 sourceindex    | source | target | prob      | result  
        1       | apple  |   dog  | 2/(2+2+1) | (2/(2+2+1))*(2/(2+2+1))
        2       | dog    |   cat  | 2/(2+2+1) | (2/(2+2+1))*(4/(2+2+1))
        3       | door   |   cat  | 1/(2+2+1) | (1/(2+2+1))*(1/(2+2+1))
        2       | dog    |   apple| 2/(2+2+1) | (2/(2+2+1))*(4/(2+2+1))
        4       | cat    |   dog  | 2/(2+2+1) | (2/(2+2+1))*(2/(2+2+1))

步骤3返回与table2 prob列相乘的结果值,依赖于相同的源索引并插入到table1

最佳答案

这是预期的结果吗?

| SOURCEINDEX | SOURCE | TARGET | T1_PROB | STEP3 |
|-------------|--------|--------|---------|-------|
|           1 |  apple |    dog |   0.400 | 0.160 |
|           2 |    dog |    cat |   0.400 | 0.160 |
|           3 |   door |    cat |   0.200 | 0.040 |
|           2 |    dog |  apple |   0.400 | 0.160 |
|           4 |    cat |    dog |   0.400 | 0.160 |

这是基于此查询:

select
        t1.sourceindex
      , t1.source
      , t1.target
      , format(t1.prob,3)          as t1_prob
      , format(t1.prob*t1.prob,3)  as step3
from table1 t1
inner join table2 t2 on t1.sourceindex = t2.sourceindex
;

这个假设的数据,而不是我已经将概率从字符串减少到指示计算的数字结果。

CREATE TABLE Table1
    (`sourceindex` int, `source` varchar(5), `target` varchar(5), `prob` decimal(12,3))
;

INSERT INTO Table1
    (`sourceindex`, `source`, `target`, `prob`)
VALUES
    (1, 'apple', 'dog', 0.400),
    (2, 'dog', 'cat', 0.400),
    (3, 'door', 'cat', 0.200),
    (2, 'dog', 'apple', 0.400),
    (4, 'cat', 'dog', 0.400)
;

CREATE TABLE Table2
    (`sourceindex` int, `source` varchar(5), `target` varchar(3), `prob` decimal(12,3))
;

INSERT INTO Table2
    (`sourceindex`, `source`, `target`, `prob`)
VALUES
    (1, 'apple', 'dog', 0.400),
    (2, 'dog', 'cat', 0.800),
    (3, 'door', 'cat', 0.200),
    (4, 'cat', 'dog', 0.400)
;

参见:http://sqlfiddle.com/#!9/80d14/1您可以在其中尝试或修改它。

关于mysql - 使用 MySQL 将包含相同索引的其他表中的值相乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25971181/

相关文章:

mysql - 查询、显示和过滤大型数据库列表

php - Symfony 2.3 实体 bool 属性只允许一行为真

php - 使用 LIKE 将字符串与包含多个单词的字符串进行匹配

sql - 使用 Access 2007 表单字段中的输入选择 SQL 查询

mysql - MySQL 中的精确小数除法

php - 尝试让 INSERT 仅插入新数据

MYSQL sum() 返回双倍分数

c# - linq 到实体 : linq query performance optimization

sql - 识别sql中不为空值的行

c# - 不能将 null 值分配给类型为 System.Int32 的成员,该类型是不可为 null 的值类型