Postgres:正则表达式和嵌套查询类似于Unix管道

时间:2009-08-24 06:17:22

标签: sql regex postgresql

命令应该执行:如果模式“*@he.com”位于不包括标题的行上,则输出1作为输出:

 user_id | username |   email   |           passhash_md5           | logged_in | has_been_sent_a_moderator_message | was_last_checked_by_moderator_at_time | a_moderator 
---------+----------+-----------+----------------------------------+-----------+-----------------------------------+---------------------------------------+-------------
       9 | he       | he@he.com | 6f96cfdfe5ccc627cadf24b41725caa4 |         0 |                                 1 | 2009-08-23 19:16:46.316272            | 

简而言之,我想用Regex连接许多SELECT命令,而不是像Unix管道那样。上面的输出来自SELECT命令。一个匹配模式的新SELECT命令应该给我1。

Related

3 个答案:

答案 0 :(得分:1)

你的意思是

  

SELECT regexp_matches( (SELECT whatevername FROM users WHERE username='masi'), 'masi');

你显然无法将记录(*)提供给regexp_matches,但我认为这不是你的问题所在,因为你提到了在主题中嵌套SQL查询的问题。

也许你的意思是

  

SELECT regexp_matches( wn, 'masi' ) FROM (SELECT whatevername AS wn FROM users WHERE username LIKE '%masi%') AS sq;

表示子查询产生多个结果的情况。

答案 1 :(得分:1)

看起来您可以使用正则表达式查询来匹配电子邮件地址:

select * from table where email ~ '.*@he.com';

如果匹配,则从此查询返回1:

select distinct 1 from table where email ~ '.*@he.com';

如果匹配,这将返回包含列的单行,否则根本没有行。还有许多其他可能的方法来构造这样的查询。

答案 2 :(得分:1)

假设您的原始查询是:

select * from users where is_active = true;

真的希望在任何专栏中匹配(由于很多原因这是个坏主意),你只想检查“*@he.com”是否匹配任何一行(顺便说一下 - 这不是正确的正则表达式!正确的是。* @ he.com,但由于没有锚点(^或$)你可以写@he.com。

select 1 from (
    select * from users where is_active = true
) as x
where textin(record_out( x )) ~ '@he.com'
limit 1;

当然您也可以选择所有列:

select * from (
    select * from users where is_active = true
) as x
where textin(record_out( x )) ~ '@he.com'
limit 1;