我这里有一些数据库模式,其中包含具有长字段的表(在MS-SQL-Server中,类型为" text",在类型为&#34的Sybase中;文本"也是),我需要检索不同的行。
表格如
create table node (id int primary key, … a few more fields … data text);
create table ref (id int primary key, node_id int, … a few more fields);
对于"节点"中的一行," ref"中可能有零行或多行。
现在我有一个像
这样的查询SELECT node.* FROM node, ref WHERE node.id = ref.node_id AND ... some more restrictions.
当" ref"中有多行时,此查询返回双面和三元组。对于某些" node_id"。
但我需要独特的行!
使用SELECT DISTINCT node.*
不起作用,因为类型为#34; text" : - (
在Sybase中有技巧,只需添加" GROUP BY node.id"对于查询,瞧!您将获得返回的唯一行。
MS-SQL-Server是否有一些类似的简单技巧?
我已经有了一个临时表的解决方案,但这似乎要慢很多,原因可能是因为传输到数据库的语句数量较多?
答案 0 :(得分:0)
看起来你正在从错误的方向接近这个问题。联接通常用于扩展键,其中相关数据存储在不同的表中。因此,每个node_id获得多行并不奇怪。
在您的查询中,您将两个表连接在一起,但是然后忽略ref中的所有内容。看起来你只是想从节点中过滤出未在ref中引用的id。如果是这种情况,那么您不想使用连接。以下将更好地工作
select *
from node
where id in (
select node_id
from ref
where [any restrictions placed on the ref table go here]
)
and [any restrictions placed on the node table go here]
此外,冒着教你糟糕的加入练习的风险,同样的事情可以通过你原本想要的方式完成,但写作更痛苦,这不是好习惯 < / p>
select node.col1, node.col2, ... , node.last_col
FROM node
inner join ref on node.id = ref.node_id
where [some restrictions.]
group by node.col1, node.col2, ... , node.last_col