Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql where子句匹配同一表中的两行以获得结果_Mysql_Sql - Fatal编程技术网

Mysql where子句匹配同一表中的两行以获得结果

Mysql where子句匹配同一表中的两行以获得结果,mysql,sql,Mysql,Sql,我有一个搜索查询,需要修改并适应我们的自定义配置文件系统,该系统使用下表: profile_key | profile_value | user_id 1 | test1 | 10 2 | test2 | 10 3 | ["test3","test4"] | 10 我需要在where子句中添加一些匹配所有行的内容,这取决于用户在搜索表

我有一个搜索查询,需要修改并适应我们的自定义配置文件系统,该系统使用下表:

  profile_key | profile_value        | user_id
       1      |    test1             |  10
       2      |    test2             |  10
       3      |    ["test3","test4"] |  10
我需要在where子句中添加一些匹配所有行的内容,这取决于用户在搜索表单中定义的内容,以获取用户id,例如:

 select user_id from table where (profile_key = 1 && profile_value regexp 'test1') && (profile_key = 3 && profile_value regexp 'test4')
如果它匹配所有定义的profile\u键和regexp,我需要获取所有的user\u id

你知道我怎样才能做到这一点吗

问候。

您是说profile_键应该是1和3。这是不可能的

您需要使用OR,而不是AND


最简单的方法是使用EXISTS:

您还可以通过内部联接来实现这一点,对于要匹配的每一行一次:

SELECT user_id
FROM users
INNER JOIN profiles p1 ON users.user_id = p1.user_id
INNER JOIN profiles p2 ON users.user_id = p2.user_id
WHERE p1.profile_key = 1 AND p1.profile_value regexp 'test1'
AND p2.profile_key = 3 AND p2.profile_value regexp 'test4'

使用类似这样的“IN”怎么样

select user_id 
from table 
where (profile_key = 1 && 'test1' IN profile_value) 
    && (profile_key = 3 && 'test4' IN profile_value )

我不会问这是否容易:P这不是一个选项,我需要知道一个用户id已经定义了这两行。您发布的内容并不是我所需要的,但是EXIST函数解决了我的问题。从表中选择用户id。从表upv中选择用户id,其中upv.profile\u key\u id='4'&&upv.profile\u值regexp aaaa&&exists从表upv中选择用户id,其中upv.profile\u key\u id='1'&&upv.profile\u值regexp阴影谢谢:D
SELECT user_id
FROM users
INNER JOIN profiles p1 ON users.user_id = p1.user_id
INNER JOIN profiles p2 ON users.user_id = p2.user_id
WHERE p1.profile_key = 1 AND p1.profile_value regexp 'test1'
AND p2.profile_key = 3 AND p2.profile_value regexp 'test4'
select user_id 
from table 
where (profile_key = 1 && 'test1' IN profile_value) 
    && (profile_key = 3 && 'test4' IN profile_value )