连接多个列的 SQL 查询
我正在尝试将两个表中的一些数据连接在一起,但在多个列上。 这是一个例子:
来源表
ID | 描述| AAAA| BBBB|
表2表
ID | 正文| ID1 | ID2 | ID3 |
其中 Table2 中的 ID1、ID2 和 ID3 是来自 Source 表的 ID
我想做一个产生结果的查询:
Table2.Text,
Source.Desc(ID1),
Source.AAAA(ID1),
Source.Desc(ID2),
Source.AAAA(ID2),
Source.Desc(ID3),
Source.AAAA(ID3)
我猜这将是一个联接,但我无法获得正确的语法...或者我使用 Union 会更好吗?
I'm trying to join some data together from 2 tables, but on several columns. here's an example:
Source table
ID | Desc| AAAA| BBBB|
Table2 table
ID | Text| ID1 | ID2 | ID3 |
where ID1, ID2 and ID3 in Table2 are ID's from the Source table
I'd like to do a query which yields the results:
Table2.Text,
Source.Desc(ID1),
Source.AAAA(ID1),
Source.Desc(ID2),
Source.AAAA(ID2),
Source.Desc(ID3),
Source.AAAA(ID3)
I'd guess this would be a join, but i can't get the syntax right... or would I be better off with a Union?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果并非所有源表都填充在 Table2 中,这仍然会给出部分结果:
If not all the Source tables are populated in the Table2, this will still give you partial results:
您需要连接到源表 3 次,每个 ID 一次。 您还可以尝试联合,看看哪个性能更好。
这是一个糟糕的表设计(应该对其进行标准化),如果可能的话,我建议您立即更改它。 应该有一个相关的表,每个 id 都在一个单独的记录中,然后你可以加入一次,这样会更高效,更容易编写代码,而且你不必在需要时更改表结构和所有查询ID4。
You need to join to the source table three times, one for each ID. You could also try a unuion to see which performs better.
This is a bad table design (it should be normalized) and I would suggest you change it now if at all possible. There shoudl bea related table with each id in a separate record, then you could join once and it would be much more efficient and far easier to write code against and you wouldn't have to change the table structure and allthe queries the day you need ID4.
您可以只使用多个联接,不是吗? 例如:
You could just use multiple joins, couldn't you? For example:
三个连接应该可以解决问题:
Three joins should do the trick: