0

我的桌子

pets
pet_lost

给我所有pets where user_id = 1...但如果还包括pet_lost数据pet_lost.pet_id = pets.id

我一直想引入,但如果有连接pets where user_id = 1,我想访问数据...pet_lost

有道理?

4

2 回答 2

0

left outer join您可以使用 a和适当的where子句将其转换为查询:

select *
from pets p left outer join
     pet_lost pl
     on pl.pet_id = p.id
where p.user_id = 1 or pl.pet_id is not null;

编辑:

您可以将其表述为:

select p.*
from pets p
where p.user_id = 1 or
      p.id in (select pl.pet_id from pet_lost);
于 2013-09-19T01:44:00.593 回答
0

我不确定你为什么有 2 个表,但据我所知,我会在 pets 列中放置一个二进制字段,以指示宠物状态是或否。

但是,如果您要保持表原样,那么您将使用“联合”查询将 2 个表放在一起。

请记住,宠物表中不能丢失宠物 ID。

我会推荐宠物表中的二进制字段并删除宠物丢失表。

于 2013-09-19T01:47:27.737 回答