SQL 获取匹配所有条件的行
我想检索与同一列上的一组条件匹配的所有行。但仅当所有条件都良好时我才想要这些行,而如果只有一个条件失败则不想要任何行。 例如,采用此表:
|id|name| --------- |1 |toto| |2 |tata|
我希望能够请求 if "tata" && “toto”在此表中。但是,当询问“tata”和“tuto”是否在其中时,如果其中一个参数不在表中,我想要一个空的响应,例如询问“toto”&&是否在其中。 “tutu”包含在表中。 我怎样才能做到这一点? 目前,我对每个参数执行一个查询,这不是很有效。我尝试了几种解决方案,包括子选择或组+拥有,但没有人按照我想要的方式工作。
感谢您的支持! 干杯
I would like to retrieve all rows matching a set of conditions on the same column. But I would like the rows only if ALL the conditions are good, and no row if only one condition fails.
For example, taking this table:
|id|name| --------- |1 |toto| |2 |tata|
I would like to be able to request if "tata" && "toto" are in this table. But when asking if "tata" and "tuto" are in, I would like an empty response if one of argument is in not in the table, for example asking if "toto" && "tutu" are included in the table.
How can I do that ?
Currently, I'am doing one query per argument, which is not very efficient. I tried several solutions including a subselect or a group+having, but no one is working like I want.
thanks for your support !
cheers
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这不是最有效的方法,但这个查询可以工作。
This isn't the most efficient way, but this query would work.
这有点模糊。如果名称是唯一的,您可以计算与 where 子句匹配的匹配行:
如果计数为 2,则您知道两者都匹配。如果名称不唯一,您可能会选择与联合中的每个 ID 匹配的第一个 ID(选择前 1 个 ID ...),并使用外部选择对这些 ID 进行计数。
即使您有任意数量的名称要匹配,您也可以使用用于构建 select 语句的任何顶级语言创建存储过程或代码。
This is a little vague. If the names are unique, you could count the matching rows that match a where clause:
If the count is 2, then you know both matched. If name is not unique you could potentially select the first ID (select top 1 id ...) that matches each in a union and count those with an outer select.
Even if you had an arbitrary number of names to match, you could create a stored procedure or code in whatever top-level language you are using to build the select statement.
如果
name
是唯一的,您可以简化为:如果不是:
或者,在 PostgreSQL、MySQL 和其他可能的环境中:
If
name
is unique you can simplify to:If it isn't:
Or, in PostgreSQL, MySQL and possibly others: