gpt4 book ai didi

mysql - 使用 MySQL 更新原始表的概率?

转载 作者:行者123 更新时间:2023-11-29 12:43:06 25 4
gpt4 key购买 nike

source | target
apple | dog
dog | cat
door | cat
dog | apple
cat | dog -----step 1.

使用 SQL 代码:

SELECT GREATEST(source,target),LEAST(source,target),COUNT(*) FROM my_table GROUP BY GREATEST(source,target),LEAST(source,target); 

将会

apple dog 2
dog cat 2
door cat 1 ------step2.

所以我想计算概率并更新到名称调用“prob”列

喜欢

source | target | prob
apple | dog | 2/(2+2+1)
dog | cat | 2/(2+2+1)
door | cat | 1/(2+2+1)
dog | apple| 2/(2+2+1)
cat | dog | 2/(2+2+1) -------step3.

从第 1 步到第 3 步我该怎么做。

最佳答案

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(source VARCHAR(12) NOT NULL,target VARCHAR(12) NOT NULL
,PRIMARY KEY(source,target)
);
INSERT INTO my_table VALUES
('apple','dog'),
('dog','cat'),
('door','cat'),
('dog','apple'),
('cat','dog');

SELECT x.*
, y.total/(SELECT COUNT(*) FROM my_table) prob
FROM my_table x
JOIN
( SELECT GREATEST(source,target) g,LEAST(source,target) l,COUNT(*) total FROM my_table GROUP BY g,l ) y
ON (y.g = x.source AND y.l = x.target)
OR (y.g = x.target AND y.l = x.source);

+--------+--------+--------+
| source | target | prob |
+--------+--------+--------+
| apple | dog | 0.4000 |
| dog | apple | 0.4000 |
| cat | dog | 0.4000 |
| dog | cat | 0.4000 |
| door | cat | 0.2000 |
+--------+--------+--------+

...或者类似的东西

关于mysql - 使用 MySQL 更新原始表的概率?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25842371/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com