MYSQL - 加入 table 在不同条件下(为空和不为空)没有联合

MYSQL - join table on different conditions (is null and is not null) without union

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  |

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

您可以使用 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 将为空。

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

select id from table1 where value is not null or id in (select distinct table1_id from table2)