4

我是 sql server 的新手,所以我真的很难在这方面翻译我的 oracle sql。通常在 oracle sql 中,我会在“in”子句中使用两个项目,但我想这在 sql server 中可能效果不佳?

这是我的数据:


笔记表

a_id     |     idxno     |     note_text

1              0               text 1 for item b_id = 61
2              1               text 2 for item b_id = 61
3              0               text 1 for item b_id = 71
4              1               text 2 for item b_id = 71
5              2               text 3 for item b_id = 71
6              0               text 1 for item b_id = 81
7              0               text 1 for item b_id = 91
8              1               text 2 for item b_id = 91

notes_bridge_table

a_id     |     b_id     

1              61       
2              61       
3              71       
4              71       
5              71       
6              81       
7              91       
8              91     

(**注意:我不保证 max(a_id) 是 notes_table 中的 max(idxno))

item_table

b_id     |     item_desc
61             desc of item 61
71             desc of item 71
81             desc of item 81
91             desc of item 91

我的愿望是显示注释表中注释最大的项目的报告。所以像:

结果

b_id     |     item_desc         |    note
61             desc of item 61        text 2 for item b_id = 61
71             desc of item 71        text 3 for item b_id = 61
81             desc of item 81        text 1 for item b_id = 61
91             desc of item 91        text 2 for item b_id = 61

我试过的:

select item_table.b_id, item_table.item_desc, 
from item_table, notes_bridge_table
where item_table.b_id = notes_bridge_table.b_id
and notes_bridge_table.a_id in
(select a_id from notes_table
 where notes_table.a_id = notes_bridge_table.a_id
 and notes_table.idxno, notes_table.a_id in
 (select max(idxno), a_id from notes_table group by a_id))

但是“and notes_table.idxno, notes_table.a_id in”的倒数第二行似乎对 sql server 无效。

4

2 回答 2

2

此查询(在 Oracle 中)

select * from t
where ( x, y ) in ( select x, y from t1 );

可以转换为在 MS-SQL 上运行的相关子查询:

select * from t
where exists (
  select 1 from t1
  where t1.x = t.x and t1.y = t.y 
);

这是 Oracle 的演示:http
://www.sqlfiddle.com/#!4/2300d/ 2 和 MS_SQL:http ://www.sqlfiddle.com/#!3/2300d/2

于 2013-10-07T18:52:26.237 回答
1

为什么复杂?可以简化:

SELECT i.b_id, i.item_desc, n.note_text
FROM item_table AS i INNER JOIN notes_bridge_table AS b
ON i.b_id = b.b_id
INNER JOIN notes_table n ON b.a_id = n.a_id
INNER JOIN
(SELECT b_id, MAX(idxno) AS idxno
    FROM notes_table AS n INNER JOIN notes_bridge_table AS b
    ON n.a_id = b.a_id
    GROUP BY b.b_id) AS b2
ON b.b_id = b2.b_id AND b2.idxno = n.idxno

而且...所有复杂性都来自完全冗余的a_id列。您的表结构不是最好的。

顺便说一句,第 3 列b_id在您的示例中显示不正确。这是正确的输出:

b_id   item_desc          note_text
------ ------------------ ---------------------------
61     desc of item 61    text 2 for item b_id = 61
71     desc of item 71    text 3 for item b_id = 71
81     desc of item 81    text 1 for item b_id = 81
91     desc of item 91    text 2 for item b_id = 91
于 2013-10-07T20:18:38.337 回答