SQL查询多个或条件 - 哪一个匹配

时间:2018-03-10 19:13:59

标签: php mysql wordpress

有没有办法在使用多个或条件时返回找到结​​果的关键字,例如:

  "SELECT post_id FROM wp_posts WHERE 
wp_posts.post_content LIKE '%ABC%' 
OR wp_posts.post_content LIKE '%DEF%' 
OR wp_posts.post_content LIKE '%GHI%'"

这是原始代码:

   SELECT DISTINCT wp_posts.ID, pm01.meta_value FROM wp_posts 
  LEFT JOIN wp_postmeta as pm01 ON wp_posts.ID = pm01.post_id AND (
    pm01.meta_key LIKE '_widget_attachments_list_%__file_img' 
    OR 
    pm01.meta_key LIKE '_widget_documents_list_%__link'
    OR
    pm01.meta_key IN ('_the_content', '_widget_text_top', '_widget_text_btm' )
  ) 
   LEFT JOIN wp_postmeta as pm02 ON wp_posts.ID = pm02.post_id AND pm02.meta_key = '_widget_type' 
  WHERE  ( wp_posts.post_type = 'post' OR ( wp_posts.post_type = 'widget' AND pm02.meta_key = '_widget_type' AND ( pm02.meta_value = 'attachments' OR pm02.meta_value = 'documents' ) ) )  
  AND wp_posts.post_status = 'publish' 
  AND
   ( 
    ( pm01.meta_key IN ('_the_content', '_widget_text_top', '_widget_text_btm' ) AND ( pm01.meta_value LIKE '%http://my-site/wp-content/uploads/2018/03/to_do.docx%') )
    OR
    ( pm01.meta_key LIKE '_widget_attachments_list_%__file_img' AND ( pm01.meta_value = 1773) )
    OR
    ( pm01.meta_key LIKE '_widget_documents_list_%__link' AND ( pm01.meta_value LIKE '%http://my-site/wp-content/uploads/2018/03/report2.docx%') )
  )

我想要达到的目的是在一个案例中返回帖子ID以及匹配的网址或附件ID。

感谢。

3 个答案:

答案 0 :(得分:1)

你可以像这样使用QUERY。

SELECT post_id,
    CONCAT_WS(','
    , IF ( wp_posts.post_content LIKE '%ABC%','ABC', NULL )
    , IF ( wp_posts.post_content LIKE '%DEF%','DEF', NULL )
    , IF ( wp_posts.post_content LIKE '%GHI%','GHI', NULL )
    ) AS KEYWORDS
FROM wp_posts
WHERE
   wp_posts.post_content LIKE '%ABC%' 
OR wp_posts.post_content LIKE '%DEF%' 
OR wp_posts.post_content LIKE '%GHI%';

答案 1 :(得分:0)

为此,您需要使用SQL case语句

SELECT post_id
       CASE WHEN wp_posts.post_content like ‘%abc%’ THEN ‘Abc’
            ELSE 
CASE WHEN wp_posts.post_content like ‘%def%’' THEN ‘def’
END
 END AS keyword
  FROM XYZ

我没有在SSMS中对此进行测试,但它应该按原样或通过较小的语法调整工作。

答案 2 :(得分:0)

由于您没有定义返回格式,因此这可能对您有用:

SELECT post_id, x.pattern
FROM wp_posts
JOIN (
    SELECT '%ABC%' as pattern
    UNION ALL 
    SELECT '%DEF%' as pattern
    UNION ALL 
    SELECT '%GHI%' as pattern
) x ON wp_posts.post_content LIKE x.pattern