SQL - 如何选择具有外部(?)条件的所有相关行
我有三个表:
player [id, name]
attribute [id, name]
player_attribute [id, player_id, attribute_id, value]
每个玩家可以有不同的属性,其中一些没有任何属性。现在我需要搜索具有某些属性的球员,例如所有编号为 11、名字为 John 的球员。此时我也知道这些属性的 id,查询的 where
部分可能如下所示: WHERE (attribute.id, attribute.value) in ((5, '11'), (18, 'John'))
我必须获取满足所有请求属性的所有玩家。
问题是我不知道整个查询应该是什么样子?我尝试过联接、嵌套选择、分组依据,但我无法使其工作。我总是得到太多或不够的行。
你能帮我吗?
编辑 感谢 aranid 我找到了一个解决方案:
select player_id from (
select * from player_attribute where (attribute.id, attribute.value) in ((5, '11'), (18, 'John')))
group by player_id
having count(*) = 2
所以,关键字 having by
使用得当:)
有什么办法可以将上面的查询转换为JOIN
语句吗?
I have three tables:
player [id, name]
attribute [id, name]
player_attribute [id, player_id, attribute_id, value]
each player can have different attributes, some of them don't have any. Now I need to search for players with certain attributes, e.g. all players that have number 11, and their first name is John. At this moment I also know id's of these attributes, where
part of my query can look like: WHERE (attribute.id, attribute.value) in ((5, '11'), (18, 'John'))
I have to get all players that meets all requested attributes.
The problem is I don't know how the whole query have to look like? I tried joins, nested selects, grouping by but I'm not able to make it work. I'm always getting too much, or not enough rows.
Can you help me please?
EDIT
Thanks to aranid I've found a solution:
select player_id from (
select * from player_attribute where (attribute.id, attribute.value) in ((5, '11'), (18, 'John')))
group by player_id
having count(*) = 2
so, the keyword was having by
used properly :)
Is there any way to transform above query into JOIN
statement?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
希望我答对了你的问题。这应该返回所有具有
(5, '11')
属性和另一个具有(18, 'John')
属性的player_id
:有什么特殊原因不将这些属性存储在
player
表中吗?这将使此类查询变得更加容易
Hope I got your question right. This should return all
player_id
s which have an attribute(5, '11')
and another one with(18, 'John')
:Any particular reason for not storing these attributes in the
player
table?This would make such queries much easier
您正在使用实体-属性-值设计,这对于任何关系数据库来说都很尴尬。
您可能会更乐意使用新的非关系数据库之一,例如 CouchDB 或 MongoDB。这些是面向文档的数据库,专门针对您所拥有的场景而设计,其中用户可以定义自己的属性,而您在设计数据库时并不知道这些属性。
You're using the Entity-Attribute-Value design, and this is just awkward for any relational database.
You'd probably be happier using one of the new non-relational databases such as CouchDB or MongoDB. These are document-oriented databases, designed for exactly the scenario you have, where users can define their own attributes and you don't know the attributes at the time you design the database.