在数据库中选择多个不同的值

时间:2010-09-27 20:58:03

标签: c# .net asp.net sql vb.net

我有这个在线测验产生随机问题,但唯一的问题是它重复了之前的问题。我的问题有限(我的表格中有10个问题,但我将问题的数量限制为5个。输出只会显示5个随机问题),我将其命名为RequiredRecords。

 question_id 
     1 
     3
     4
     7 
     9 
     14 
     15
     24
     26
     29

应该随机输出

  question_id 
     3
     4
     9 
     14 
     24

我试图访问this question,但它无法解决我的问题。下面是我使用的一些代码和SQL语句。

我发现我对创建随机问题的查询没有任何问题,我可以在没有重复的情况下显示它,但是我的其他代码出现问题导致程序重复。请帮帮我。


使用VS2008 3.5后面的代码

Partial Class Student_DetailView
Inherits System.Web.UI.Page

Shared TotalRecords As Integer
Private sqlda As SqlDataAdapter
Private dt As DataTable

Private Function CreateConnection() As SqlConnection
    Dim _connectionString As String = ConfigurationManager.ConnectionStrings("LMSConnectionString").ConnectionString
    Return New SqlConnection(_connectionString)
End Function

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim quiz_id As Integer
    quiz_id = Session("quiz_id")

    Dim query As String = "SELECT COUNT(*) AS TotalRecords FROM tblQuizQuestion WHERE (quiz_id = '" & quiz_id & "')"
    Dim dt As DataTable = GetRecords(query)
    TotalRecords = Convert.ToInt32(dt.Rows(0)("TotalRecords"))

    getQuestions()
End Sub

Public Function GetRecords(ByVal Query As String) As DataTable
    Dim connection As SqlConnection = CreateConnection()
    connection.Open()
    sqlda = New SqlDataAdapter(Query, connection)
    dt = New DataTable()
    sqlda.Fill(dt)
    connection.Close()
    Return dt
End Function

Public Function RandomNumbers(ByVal max As Integer) As ArrayList
    Dim lstNumbers As New ArrayList()
    Dim rndNumber As New Random()
    Dim number As Integer = rndNumber.[Next](1, max + 1)
    lstNumbers.Add(number)
    Dim count As Integer = 0
    Do
        number = rndNumber.[Next](1, max + 1)
        If Not lstNumbers.Contains(number) Then
            lstNumbers.Add(number)
        End If
        count += 1
    Loop While count <= 10 * max
    Return lstNumbers
End Function

Public Function GetRandomNumbersCSV(ByVal max As Integer, ByVal req As Integer) As String
    Dim CSV As String = ""
    Dim lstNumbers As ArrayList = RandomNumbers(max)
    For i As Integer = 0 To req - 1
        CSV += lstNumbers(i).ToString() & ","
    Next
    CSV = CSV.Remove(CSV.Length - 1)
    Return CSV
End Function

Protected Sub buttonNext_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles buttonNext.Click
    If Not Session("dt") Is Nothing Then
        getQuestions()
        Try
            ' Save off previous answers
            Dim dr As System.Data.DataRowView
            dr = CType(questionDetails.DataItem, System.Data.DataRowView)

            ' Create Answer object to save values
            Dim a As Answer = New Answer()
            a.CorrectAnswer = dr("answer").ToString()
            a.UserAnswer = answerDropDownList.SelectedValue.ToString()

            Dim al As ArrayList
            al = CType(Session("AnswerList"), ArrayList)
            al.Add(a)

            Session.Add("AnswerList", al)

        Catch ex As Exception

            Response.Redirect("default.aspx")
        End Try
        If questionDetails.PageIndex = questionDetails.PageCount - 1 Then
            ' Go to evaluate answers
            Response.Redirect("results.aspx")
        Else
            questionDetails.PageIndex += 1

        End If

        If questionDetails.PageIndex = questionDetails.PageCount - 1 Then
            buttonNext.Text = "Finished"
        End If
    End If
End Sub

Private Sub getQuestions()
    Dim RequiredRecords As Integer
    RequiredRecords = 5
    Dim CSVData As String, query As String
    Dim quiz_id As Integer
    quiz_id = Session("quiz_id")
    If TotalRecords >= RequiredRecords Then
        CSVData = GetRandomNumbersCSV(TotalRecords, RequiredRecords)

        query = "SELECT distinct question_id,quiz_question, choice1, choice2, choice3, choice4, answer, quiz_id FROM " & _
                "(SELECT question_id,quiz_question, choice1, choice2, choice3, choice4, answer, quiz_id , ROW_NUMBER() OVER(ORDER BY rand()) " & _
                "AS RowID FROM tblQuizQuestion WHERE quiz_id = '" & quiz_id & "') TempTable WHERE RowID IN(" & CSVData & ")"
        dt = GetRecords(query)
        Session("dt") = dt
        questionDetails.DataSource = dt
        questionDetails.DataBind()
    Else
        Response.Write("Required Records must be greater than Requried Records.")
    End If
End Sub

End Class

2 个答案:

答案 0 :(得分:0)

你应该能够像这样随机化你的问题

  

选择前5个QuestionID,newID()为   RandomString来自问题排序依据   RandomString

newid()是一个关键字,它会为您提供随机指导,然后按

对问题进行排序

答案 1 :(得分:0)

请看一下这个答案,找出一种方法,以可预测的方式随机化来自数据库的条目,以便在您离开的地方恢复... Linq Orderby random ThreadSafe for use in ASP.NET

您可以通过特定值(例如用户ID,用户ID加上日期,......)为随机数生成器播种,然后轻松地从数据库中获取每个项目,而不需要知道除了您想要的项目的索引之外的任何内容随机序列。