您可能想要解决这个问题的方法是有两个表来存储有关彩票的信息:
lottery_tickets:存储有关每张彩票的信息:
lottery_tickets
----------------------
id [PK]
first_name
last_name
date_given
...
lottery_ticket_numbers:存储相应的彩票号码:
lottery_ticket_numbers
----------------------
id [PK](FK)
number [PK]
position
字段上两者id
通过1:N识别关系连接,每张彩票在lottery_ticket_numbers
表中有8行对应。该position
字段将跟踪整个数字字符串中每个数字的位置 (1-8)。
这将允许您通过将表格连接在一起并将范围缩小到具有所有匹配号码的彩票来轻松找出中奖彩票:
SELECT
a.*,
GROUP_CONCAT(b.number ORDER BY position SEPARATOR '-') AS lottery_number
FROM
lottery_tickets a
INNER JOIN
lottery_ticket_numbers b ON a.id = b.id
WHERE
b.number IN (07,12,34,40,59,80,88,89)
GROUP BY
a.id
HAVING
COUNT(b.number) = 8
结果集将如下所示:
id | first_name | last_name | date_given | lottery_number
--------------------------------------------------------------------------------
823 | Zane | Bien | 2012-01-01 | 34-80-07-89-12-40-59-88
2321 | Jeff | Clark | 2012-01-14 | 59-07-88-40-12-34-80-89
注意:
- 如果您使用的是 MySQL,该
GROUP_CONCAT()
函数将 XX-XX-XX-XX-XX-XX-XX-XX 格式的中奖彩票号码与该人获得的原始号码中的号码合并。如果您不使用 MySQL,我不确定其他 DBMS 中是否存在类似功能。
现在您可能还想存储有关实际中奖彩票号码的数据。为此,您还将以几乎相同的方式使用两张表:一张用于彩票号码,另一张用于对应的号码:
查询中奖彩票:
SELECT
a.*,
GROUP_CONCAT(b.number ORDER BY position SEPARATOR '-') AS lottery_number
FROM
lottery_tickets a
INNER JOIN
lottery_ticket_numbers b ON a.id = b.id
WHERE
b.number IN
(
SELECT number
FROM winning_numbers_numbers
WHERE id = <id of a particular lottery number>
)
GROUP BY
a.id
HAVING
COUNT(b.number) = 8
与前面的查询几乎相同,只是现在数字列表是来自子查询的结果集。
显示中奖彩票号码很简单。前任:
检索所有中奖号码及其开奖日期;将他们的数字字符串显示为按升序排列的数字,并按最近提取的数字排序:
SELECT
GROUP_CONCAT(b.number ORDER BY b.number SEPARATOR '-') AS winning_number,
a.date_pulled
FROM
winning_numbers a
INNER JOIN
winning_numbers_numbers b ON a.id = b.id
GROUP BY
a.id
ORDER BY
a.date_pulled DESC
请注意,当您插入中奖号码时,您完全不必担心您插入的号码的顺序。由于它们始终按升序显示,因此ORDER BY
inGROUP_CONCAT()
会为您处理。
现在让我们看看如果您使用基于列的方法(将中奖号码和彩票号码存储为单行,但每个号码有八列),您将需要做什么:
假设架构:
winning_numbers(id, date_pulled, n1, n2, n3, n4, n5, n6, n7, n8)
ticket_numbers(id, fname, lname, date_given, n1, n2, n3, n4, n5, n6, n7, n8)
查找给定彩票号码的所有中奖彩票:
SELECT
a.*
FROM
ticket_numbers a
INNER JOIN
winning_numbers b ON
a.n1 IN (b.n1, b.n2, b.n3, b.n4, b.n5, b.n6, b.n7, b.n8) AND
a.n2 IN (b.n1, b.n2, b.n3, b.n4, b.n5, b.n6, b.n7, b.n8) AND
a.n3 IN (b.n1, b.n2, b.n3, b.n4, b.n5, b.n6, b.n7, b.n8) AND
a.n4 IN (b.n1, b.n2, b.n3, b.n4, b.n5, b.n6, b.n7, b.n8) AND
a.n5 IN (b.n1, b.n2, b.n3, b.n4, b.n5, b.n6, b.n7, b.n8) AND
a.n6 IN (b.n1, b.n2, b.n3, b.n4, b.n5, b.n6, b.n7, b.n8) AND
a.n7 IN (b.n1, b.n2, b.n3, b.n4, b.n5, b.n6, b.n7, b.n8) AND
a.n8 IN (b.n1, b.n2, b.n3, b.n4, b.n5, b.n6, b.n7, b.n8) AND
b.id = <winning number id>
IN
如果你要问我,那真是一大堆……!!!
这种方法的优点是您不需要特定于 MySQL 的GROUP_CONCAT
函数来显示票号。