【问题标题】:MYSQL - join table on different conditions (is null and is not null) without unionMYSQL - 在没有联合的情况下在不同条件下连接表(为空且不为空)
【发布时间】:2023-03-06 01:46:01
【问题描述】:
table1
---+---------
id | value
---+---------
1  | (NULL)
2  | 'string'
3  | (NULL)

table2
---+-----------
id | table1_id
---+-----------
1  | 3

我可以通过执行得到我的结果

select table1.id from table1 where table1.value is not null
union
select table1.id from table1 right join table2 on table1.id=table2.table1_id

所以我需要得到的是

---+--
id | 
---+--
2  |
3  |

但我不能使用联合,因为我应该使用不支持联合的 yii1.1 CDbCriteria 我尝试了不同的连接类型,但没有结果。

【问题讨论】:

    标签: mysql join yii


    【解决方案1】:

    您可以使用 LEFT JOIN 以这种方式编写查询:

    SELECT table1.id
    FROM
      table1 LEFT JOIN table2
      ON table1.id=table2.table1_id
    WHERE
      table1.value IS NOT NULL
      or table2.table1_id IS NOT NULL
    

    由于您使用的是 LEFT JOIN,因此当连接不成功时,table2.table1_id 将为空。

    【讨论】:

      【解决方案2】:

      为什么你需要一个连接,这个简单的查询应该可以做到:

      从 table1 中选择 id,其中 value 不为 null 或 id in (select 与 table2 不同的 table1_id)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-10-10
        • 2017-12-25
        • 2021-02-21
        • 2022-10-01
        • 2011-12-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多