基于一组命名属性/值的查询
我正在处理一组本质上是属性/值对的内容(实际上还有很多内容,但为了这个问题我正在简化)。 实际上,您可以将表格视为这样:
实体(实体 ID、属性名称、属性值) PK=实体 ID、属性名称
目标 (TargetID,AttributeName,AttributeValue) PK=TargetID,AttributeName
如何使用 SQL 查询 EntityID、TargetID 集合,其中实体拥有目标的所有属性以及相应的值?
编辑(根据要求的 DDL):
CREATE TABLE Entities(
EntityID INTEGER NOT NULL,
AttributeName CHAR(50) NOT NULL,
AttributeValue CHAR(50) NOT NULL,
CONSTRAINT EntitiesPK PRIMARY KEY (EntityID,AttributeName)
);
CREATE TABLE Targets(
TargetID INTEGER NOT NULL,
AttributeName CHAR(50) NOT NULL,
AttributeValue CHAR(50) NOT NULL,
CONSTRAINT TargetsPK PRIMARY KEY (TargetID,AttributeName)
);
I am working with a set of what is essentially Attribute/Value pairs (there's actually quite a bit more to this, but I'm simplifying for the sake of this question). Effectively you can think of the tables as such:
Entities (EntityID,AttributeName,AttributeValue) PK=EntityID,AttributeName
Targets (TargetID,AttributeName,AttributeValue) PK=TargetID,AttributeName
How would you query with SQL the set of EntityID,TargetID for which an Entity has all the attributes for a target as well as the corresponding value?
EDIT (DDL as requested):
CREATE TABLE Entities(
EntityID INTEGER NOT NULL,
AttributeName CHAR(50) NOT NULL,
AttributeValue CHAR(50) NOT NULL,
CONSTRAINT EntitiesPK PRIMARY KEY (EntityID,AttributeName)
);
CREATE TABLE Targets(
TargetID INTEGER NOT NULL,
AttributeName CHAR(50) NOT NULL,
AttributeValue CHAR(50) NOT NULL,
CONSTRAINT TargetsPK PRIMARY KEY (TargetID,AttributeName)
);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
好的,我认为经过多次尝试和编辑,这个解决方案最终有效:
测试数据:
测试结果:
为了回应您的评论,这里是一个颠倒表的查询:
这是输出,给出与上面相同的输入数据。
Okay, I think after several tries and edits, this solution finally works:
Test data:
Test results:
To respond to your comment, here is a query with the tables reversed:
And here's the output, given the same input data above.
我喜欢这类问题,但我认为希望OP至少提供为表创建脚本甚至一些示例数据并不是没有道理的。
我喜欢听谁同意,谁不同意。
I like these kind of questions but I think it is not unreasonable to hope that the OP provides at least create scripts for the table(s) and maybe even some sample data.
I like to hear who agrees and who disagrees.
edit1:
如果目标表中存在与实体表中不匹配的行是可以的,则解决方案简化为:
edit 2:
这并不容易理解OP的确切要求。
这是一个新的 select 语句。 我希望他能测试我所有选择的陈述以理解其中的差异。 我希望他有好的测试用例并且知道他想要什么。
edit1:
If it is OK to have rows in the target table that have no match in the entities table, the solution simplifies to:
edit 2:
It is not easy to understand the exact requirements of the OP.
Here is a new select statement. I hope he will test all my select statements to understand the differences. I hope he has good test cases and knows what he wants.