【问题标题】:Select all records with same column value after search搜索后选择具有相同列值的所有记录
【发布时间】:2021-02-10 13:26:06
【问题描述】:

我有一个名为“表格”的表格,看起来像这样

ID entry_id content
1 1 text
2 1 rand txt
3 1 another rand txt
4 2 new entry

我需要根据内容搜索这个表(例如SELECT * FROM forms WHERE content LIKE 'text';),如果找到该记录,则需要选择所有其他具有相同entry_id的记录。

例如,如果通过搜索查询找到 ID 为 1 的记录,则 ID 为 2 和 3 的记录也应被选中,因为它们属于同一条目。

【问题讨论】:

    标签: mysql sql adonis.js


    【解决方案1】:
    SELECT t2.* 
    FROM forms t1
    JOIN forms t2 USING (entry_id) 
    WHERE t1.content LIKE 'text';
    

    记住 - 不带模式符号的 LIKE 仅搜索直接匹配(即等于 =)。

    【讨论】:

      【解决方案2】:

      一种方法使用exists

      select f.*
      from forms f
      where exists (select 1
                    from forms f2
                    where f2.id = f.id and
                          f.content like 'text'
                   );
      

      你也可以使用窗口函数:

      select f.*
      from (select f.*,
                   sum( f.content like 'text' ) over (partition by id) as num_text
            from forms f
           ) f
      where num_text > 0;
      

      【讨论】:

        【解决方案3】:

        试试:

        SELECT *
        FROM forms AS f1 INNER JOIN forms AS f2 ON f1.entry_id = f2.entry_id
        WHERE f1.content LIKE 'text'
        

        【讨论】:

          【解决方案4】:

          您的查询应该是这样的。您可以使用嵌套查询。

          SELECT * FROM forms
          WHERE entry_id IN
          (SELECT entry_id FROM forms WHERE content LIKE '%text%')
          

          【讨论】:

            猜你喜欢
            • 2013-11-10
            • 2021-03-22
            • 1970-01-01
            • 1970-01-01
            • 2018-12-06
            • 2019-01-28
            • 2015-02-15
            • 2016-01-26
            • 1970-01-01
            相关资源
            最近更新 更多