嵌套 SQL 语句
我有一个人员表,还有一个联系人类型表(电子邮件、电话等) 和一个用于保存人员联系人的联结表。
我想构建一个查询来获取一条记录中每个人的电子邮件、电话、邮政地址,
因此我将有 4 列结果集用户名、电话、电子邮件、邮政地址
当我使用 SQL Server 2000 时,XML 不是一个选项。
任何帮助使其发挥作用的帮助将不胜感激。
I have a table for persons, anothor for types of contacts(email, tel, etc.)
and a junction table to save person contacts.
I'w like to construct a query to get email, tel, po for each person in one record,
so I will have 4 columns result set UserName, Tel, Email, PO
As I use SQL Server 2000, XML is not an option.
Any help to get this to work will be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您未能提供有关列的任何有用的详细信息,因此我不得不猜测,但我认为您正在寻找类似的内容。
退货
You have failed to provide any useful details about columns so I had to guess but I think you are looking for something like.
Returns
我认为你想要这样:
所以你基本上加入联系人表 3 次,因为联系人表包含 3 种不同形式的联系人。这是一种多态方法,它不能很好地映射到 SQL
这个查询的结果应该是这样的:
我认为马丁的解决方案也可以工作,但我对 CASE-WHEN-THEN-END 不太满意
I think you want this:
So you basically join on the contacts table 3 times because the contacts table contains 3 different forms of contacts. This is a polymorphic approach and it doesn't map well to SQL
The result of this query should be something like:
I think martin's solution will work as well but I'm not too happy with the CASE-WHEN-THEN-END
我们必须猜测您的架构,因为您没有在问题的初始版本中向我们提供关键信息:
假设的架构
可能的查询
请注意,应强制执行一些复杂的约束使查询正常工作。第一个是给定人员有零个或一个电子邮件地址、零个或一个电话号码以及零个或一个 PO(这是邮局地址吗?)。如果某人拥有多个这些条目,您根本不会告诉我们什么可能是合适的输出。而且约束执行起来很复杂,因为最简单的版本需要对用户名和联系人类型的组合进行唯一约束,但这些列不会一起存储在任何单个表中。
We have to make guesses about your schema because you didn't give us the crucial information in the initial version of the question:
Assumed schema
Possible query
Note that there are some complex constraints that should be enforced to make the query work sanely. The primary one is that there is either zero or one email address for a given person, and zero or one telephone number, and zero or one PO (is that a Post Office address?). You simply don't tell us what might be appropriate output if someone has more than one of any of these entries. And the constraints are complex to enforce because the simplest version would require a unique constraint on the combination of user name and contact type, but those columns are not stored together in any single table.