DISTINCT无法正常工作

时间:2014-09-03 08:10:39

标签: sql sql-server sql-server-2008 tsql

我有一个查询,我需要显示具有不同ID的数据

 Query= "SELECT * FROM (" &_

 " SELECT DISTINCT t.TICKET_ID as TICKET_ID, "&_
 " ROW_NUMBER() OVER (ORDER BY t.TICKET_ID DESC)NUM,"&_
" t.SHORT_DESCRIPTION as SHORT_DESCRIPTION, "&_
" p.TITLE as product_name"&_
" FROM T_TICKET as t,T_USER_PRODUCT as up "&_
" ,T_USER as u, T_PRODUCT as p" & _
 pReleaseFrom & _
" WHERE u.USER_ID=t.EDITOR_ID  AND not t.SHORT_DESCRIPTION is null" & _
 StateCondition & _

" ) A"& _   
" WHERE NUM BETWEEN " & Session("Start") & " AND " & Session("Endi")
Query=Query & " ORDER BY "&orderBy 

但有些行并不明显,甚至没有通过t.TICKET_ID DESC进行排序。

请帮忙吗?

2 个答案:

答案 0 :(得分:2)

一个问题在于:

ROW_NUMBER() OVER (ORDER BY t.TICKET_ID DESC) NUM

当您选择所有rownumbers时,它们是1,2,3,4,5之类的数字,并且按照设计它们是不同的。所以来自不同行号的SELECT DISTINCT没有意义。假设TICKET_ID是唯一的主键。

另一件事是您可能在部件中遇到问题:

FROM T_TICKET as t, T_USER_PRODUCT as up ,T_USER as u, T_PRODUCT as p

你实际上在做CROSS JOIN - 我不确定它是否符合设计要求。

同样以您的方式生成SQL命令容易受到SQL注入攻击。您应该使用参数化查询。

答案 1 :(得分:0)

" The DISTINCT keyword eliminates duplicate rows from the results of a SELECT statement&#34 ;.这意味着如果您执行SELECT DISTINCT,结果集中将不会出现重复的。整行查看该行以确定行是否是不同的,而不是您想象的行中的某个特定列。