将数百行数据与另一个表中的数据进行比较

时间:2016-09-17 23:14:45

标签: mysql sql

我有一个有趣的问题实际上让我感到非常悲伤。

我有2张化妆相同的桌子。一张桌子持有给定抽奖的中奖彩票号码,另一张桌子持有500张随机生成的#34;门票"那次抽奖。

我正在尝试编写一些代码,告诉我500张门票中有多少有3个匹配的号码,4个匹配的号码,5个匹配的号码,当然还有6个匹配的号码。

两个表的表结构是

id,playDate,num1,num2,num3,num4,num5,num6。

这是我所处的地方,我知道在任何人说什么之前这是不正确的。真的在这里挣扎:

SELECT count(*) AS c, w.*, l.* 
FROM winningNums AS w, lottoNums AS l
WHERE w.playDate = "2016-10-10"
AND l.playDate = "2016-10-10"
AND l.num1 (
w.num1, w.num2, w.num3, w.num4, w.num5, w.num6 
)

我也在打击这样的事情

SELECT * 
FROM winningNums AS w
INNER JOIN lottoNums AS l
ON w.playDate = l.playDate
AND w.num1 = l.num1
AND w.num2 = l.num2
AND w.num3 = l.num3
AND w.num4 = l.num4
AND w.num5 = l.num5
AND w.num6 = l.num6

我面临的主要问题是3场比赛的胜利可能来自num1,num3和num4(来自票证),与num2,num5和num6(来自中奖号码)相匹配。

帮助: - )

2 个答案:

答案 0 :(得分:2)

SELECT l.*,
    (l.num1 IN (w.num1, w.num2, w.num3, w.num4, w.num5, w.num6)) +
    (l.num2 IN (w.num1, w.num2, w.num3, w.num4, w.num5, w.num6)) +
    (l.num3 IN (w.num1, w.num2, w.num3, w.num4, w.num5, w.num6)) +
    (l.num4 IN (w.num1, w.num2, w.num3, w.num4, w.num5, w.num6)) +
    (l.num5 IN (w.num1, w.num2, w.num3, w.num4, w.num5, w.num6)) +
    (l.num6 IN (w.num1, w.num2, w.num3, w.num4, w.num5, w.num6))
    AS hits
FROM winningNums AS w
CROSS JOIN lottoNums AS l
WHERE w.playDate = "2016-10-10"
  AND l.playDate = "2016-10-10"
HAVING hits >= 3
ORDER BY hits DESC

这会将票证中的每个号码与彩票中的每个号码进行比较。并且将添加所有匹配/匹配。

答案 1 :(得分:0)

您可以使用IN语句查找返回1或0的匹配项,然后将它们添加到计数匹配项数... 然后使用HAVING检查匹配> = 3这样。

SELECT lot.id as lotid,draw.id as drawid,
     (draw.num1 IN (lot.num1,lot.num2,lot.num3,lot.num4,lot.num5,lot.num6))
   + (draw.num2 IN (lot.num1,lot.num2,lot.num3,lot.num4,lot.num5,lot.num6))
   + (draw.num3 IN (lot.num1,lot.num2,lot.num3,lot.num4,lot.num5,lot.num6))
   + (draw.num4 IN (lot.num1,lot.num2,lot.num3,lot.num4,lot.num5,lot.num6))
   + (draw.num5 IN (lot.num1,lot.num2,lot.num3,lot.num4,lot.num5,lot.num6))
   + (draw.num6 IN (lot.num1,lot.num2,lot.num3,lot.num4,lot.num5,lot.num6))
   AS matches
FROM lot
  INNER JOIN draw
HAVING matches >= 3;

sqlfiddle