【问题标题】:Using Substring_Index with data from a second table将 Substring_Index 与第二个表中的数据一起使用
【发布时间】:2021-01-16 02:56:10
【问题描述】:

作为我previous question的后续行动:

我想选择wp_posts 表中匹配的所有内容:

  1. post_type = "answer"
  2. post_type = "question"
  3. post_type 包含修订,前面是前面任一标准的 ID。例如:21-revision-v110903-revision-v1 此处我要选择那些帖子的第一个数字部分与前2个要求中选择的帖子的ID匹配的帖子。

我现在构建了一个新表 ap_qa,其中包含符合上述条件 1 或 2 的帖子的所有 ID。

现在选择符合条件 3 的案例,我想使用 Substring_Index(),因为它允许在字符串中进行匹配。

我当前的代码是:

SELECT * 
FROM `wp_posts` p 
WHERE p.post_type IN ('answer', 'question') OR
Substring_Index(p.post_Type,'-revision',1) IN QA.ID

where 后面的第一条规则是满足条件 1 和 2,最后一行是满足条件 3。但是我的语法是无效的,正如返回的那样。

错误信息如下(荷兰语):

#1064 - Er is iets fout in de gebruikte syntax bij 'QA.ID' in regel 4

【问题讨论】:

    标签: mysql sql select subquery where-clause


    【解决方案1】:

    您的 systqax 错误,因为您的错误消息表明 使用 zhis 之类的东西

    SELECT * 
    FROM `wp_posts` p 
    WHERE p.post_type IN ('answer', 'question') 
    OR
     QA.ID LIKE CONCAT(Substring_Index(p.post_Type,'-revision',1) ,'%')
    LIMIT 0, 25
    

    【讨论】:

      【解决方案2】:

      你需要一个子查询来返回表ap_qa的id:

      SELECT * 
      FROM `wp_posts` p 
      WHERE p.post_type IN ('answer', 'question') 
         OR SUBSTRING_INDEX(p.post_Type,'-revision',1) IN (SELECT ID FROM ap_qa) 
      

      或者不带表ap_qa

      SELECT * 
      FROM `wp_posts` p 
      WHERE p.post_type IN ('answer', 'question') 
         OR SUBSTRING_INDEX(p.post_Type,'-revision',1) IN (
               SELECT ID FROM `wp_posts` 
               WHERE p.post_type IN ('answer', 'question')
             )
      

      【讨论】:

        【解决方案3】:

        我现在构建了一个新表 ap_qa,其中包含来自符合上述条件 1 或 2 的帖子的所有 ID。

        您根本不需要临时表。您可以在单个查询中直接从原始表中获得所需的结果:

        select *
        from wp_posts wp
        where post_type in ('answer', 'question') and exists (
            select 1
            from wp_posts wp1
            where 
                wp1.post_type in ('answer', 'question') 
                or wp1.id = substring_index(wp.post_type, '-revision', 1)
        )
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-01-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多