2014-01-14 2 views
0

목표 : 사용자 ID와 SiteID가 일치하는 데이터베이스는 사용자 ID와 SiteID가 일치하면 세부 정보를 볼 수 있습니다.SQL Select Count WHERE 절로

생각 : Count (Distinct ...)를 사용하여 존재하는지 확인해 보았습니다. 그런 다음 0이 아닌 값을 반환하면 세부 사항을 볼 수 있음을 알게됩니다.

가장 좋은 방법입니까?

문제 :이 방법을 사용하려고하면 WHERE 절을 사용할 수 없습니다.

오류 : 재생 한 오류는 본질적으로 WHERE 절을 가질 수 없다고 말합니다. 정확합니까?

코드 : 쿼리에 where 절에 아무 문제가 없습니다

Dim ConnectionString As String = System.Configuration.ConfigurationManager.ConnectionStrings("mySQL").ToString() 
       Using connection = New SqlConnection(ConnectionString) 
        Using command As New SqlCommand("Select Count(Distinct(UserID)) FROM tblTable where UserID= '" & Session.Item("UserID").ToString & "'", connection) 

         connection.Open() 
         Dim result = command.ExecuteScalar() 

         lblResult.Text = result 

         connection.Close() 
        End Using 
       End Using 
+1

나는 당신이 실행하려고하는 쿼리를 빌드하기 위해'string' 변수를 선언 할 것이다. 그런 다음 이것을 디버깅 목적으로 사용할 수 있습니다. –

+0

이 쿼리에 어떤 오류가 있습니까? 사용중인 db는 무엇입니까? –

+1

참고 사항 : 전체 SQL 문자열 (SQL 주입, 성능)을 빌드하는 것이 아니라 매개 변수가있는 쿼리를 사용해야합니다. –

답변

1

을 나는 코드를 시도하고 내가 할 Session.Item ("UserId")이 제대로 설정되지 않는 한 문제가있는 곳을 볼 수 없습니다. 세션이 없으므로 콘솔 응용 프로그램에서 즉석에서 보았습니다. Count (Distinct (UserId))가 항상 1을 반환하기 때문에 정확히 무엇을 하려는지 알아 내려고합니다. 특정 userId를 요청한 후 별개로 질문 한 다음 계산합니다. 따라서 1 명의 사용자가 100 번을 반환하고, 별개의 사용자 만 목록에 표시하므로 1이 반환됩니다.

Dim ConnectionString As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConnectionString").ToString() 
    Using connection = New SqlConnection(ConnectionString) 

     Using command As New SqlCommand() 
      Dim userId As String = "3" 
      command.Connection = connection 
      command.CommandText = "Select Count(Distinct(UserId)) FROM tblTable _ 
             where UserId= '" & userId & "'" 

      connection.Open() 
      Dim result = command.ExecuteScalar() 

      Console.WriteLine(result) 

      connection.Close() 
     End Using 
    End Using 

사용자가 있는지 확인하려는 경우 다음 코드를 시도하십시오. 이것은 사용자 ID가 포함 된 행 수에 당신을 말할 것이다

 Dim ConnectionString As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConnectionString").ToString() 
    Using connection = New SqlConnection(ConnectionString) 

     Using command As New SqlCommand() 
      Dim userId As String = "3" 
      command.Connection = connection 
      command.CommandText = "Select Count(UserId) FROM tblTable _ 
             where UserId= '" & userId & "'" 

      connection.Open() 
      Dim result = command.ExecuteScalar() 

      Console.WriteLine(result) 

      connection.Close() 
     End Using 
    End Using 

테이블에

당신은 또 다른 이야기

 Dim ConnectionString As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConnectionString").ToString() 
    Using connection = New SqlConnection(ConnectionString) 

     Using command As New SqlCommand() 
      Dim userId As String = "3" 
      command.Connection = connection 
      command.CommandText = "Select UserID, Count(SiteId) FROM tblTable where _ 
          UserId= '" & userId & "'" & " Group By UserId" 

      connection.Open() 
      Dim dataReader = command.ExecuteReader() 
      Do While dataReader.Read() 
       Console.WriteLine(_ 
        vbTab & "UserId: {0}" & vbTab & "SiteID Count: {1}", _ 
       dataReader(0), dataReader(1)) 
      Loop 
      connection.Close() 
     End Using 
    End Using 
입니다 카운트로 사용자 ID/사이트 Comination를보고 싶다면

나는 올바른 트랙을 가져와야한다고 생각한다.

+0

나는 다른 두 페이지에서 잘 작동 할 것입니다. – indofraiser

0

:

select count(distinct userid) 
from tblTable 
where UserID= '" & Session.Item("UserID").ToString & "'"; 

일부 SQL 엔진에서, userid 주위에 추가 괄호가 허용되지 않는 것이 가능하다.

공정한 처리를해야하기 때문에 행이 있는지 판별하는 가장 좋은 방법은 아닙니다.

select 1 
from tblTable 
where UserID= '" & Session.Item("UserID").ToString & "'" 
limit 1 

을하거나 (SQL Server의 /베이스) : 대신 (엔진이 limit을 지원하는 경우),이 쿼리에 의해 반환되는 행의 수를 확인

select top 1 1 
from tblTable 
where UserID= '" & Session.Item("UserID").ToString & "'" 
limit 1;