【问题标题】:select rows based on column1 and column2 that have value of column 1根据 column1 和 column2 选择具有第 1 列值的行
【发布时间】:2022-01-17 14:12:43
【问题描述】:

我有一个这样的 SQL 表:

ID,     ID2,      category.   date,     txt
 1      null         1        Y-m-d     text
 2      null         1        Y-m-d     text
 3      4            1        Y-m-d     text
 4      null         2        Y-m-d     text
 5      6            1        Y-m-d     text
 6      null         3        Y-m-d     text
 7      null         5        Y-m-d     text

我尝试选择所有类别 = 1 的行,例如 id: 1,2,3,5,6,但我也想要 id 为 4,6 的行,即使它们的类别不是 1,但它们在 ID2 中具有类别 1 的行。

Select * from table WHERE category=1 AND ....  LIMIT 20

所以结果将是 1,2,3,4,5,6

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    在此处使用自联接:

    SELECT t1.*
    FROM yourTable t1
    LEFT JOIN yourTable t2
        ON t2.ID2 = t1.ID
    WHERE
        t1.category = 1 OR t2.category = 1;
    

    Demo

    【讨论】:

      【解决方案2】:

      您可以使用exists

      select *
      from t
      where category=1
        or exists (select * from t t2 where t2.id2=t.id and t2.category=1)
      

      【讨论】:

        【解决方案3】:

        你想要怎样的结果?

        第一:

        从测试 a 中选择 id t,其中 a.category='1' 并且 id 不为空

        联合所有

        从测试 a 中选择 id2 t,其中 a.category='1' 且 id2 不为空

        id
        1
        2
        3
        5
        4
        6

        秒:

        select a.* from test a left join test b on a.id=b.id 其中 a.category='1' 或 b.category='1'

        id id2 category
        1 1
        2 1
        3 4 1
        5 6 1

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-05-05
          • 1970-01-01
          • 2021-06-06
          • 2021-01-30
          • 1970-01-01
          • 2020-03-17
          • 2016-01-01
          相关资源
          最近更新 更多