选择一个表中没有的行与另外两个表相对应?

时间:2014-09-09 01:48:47

标签: mysql sql laravel-4 eloquent

我有三个表,我试图在Eloquent中构建一个查询,只获取第三个表中不存在的两个表中的行。

一个是表histories,它引用了另外两个表schedulestemplates。如果有模板计划历史记录,我不希望得到该计划。

通常情况下,我希望可以在第三个表LEFT JOIN上使用IS NULL来完成,但这在此实例中不起作用。到目前为止,我尝试的每个查询总是返回空列以及我不想要的行。

以下是相关架构和示例查询的小提琴: http://sqlfiddle.com/#!2/28aad/5

如何构建查询以获得所需的结果?

3 个答案:

答案 0 :(得分:0)

您的查询应如下所示:但是您的查询未返回任何结果,因为每个计划/模板都有历史记录。

select 
    histories . *,
    histories.id as 'history_id',
    schedules . *,
    schedules.id as 'schedule_id'
from
    schedules
left join
    histories ON schedules.id = histories.schedule_id
        and schedules.template_id = histories.template_id
where
    schedules.schedulable_id = 16
    and schedules.schedulable_type = 'Item'
    and histories.id IS NULL

答案 1 :(得分:0)

假设您希望获取schedules表中不在histories表中的行,您的雄辩查询将是这样的:

//Fetches list of schedule IDs from Histories table
$schedule_ids = Histories::distinct()->lists('schedule_id')
//Get list of all schedules which are not present in Histories table
$queryresult = Schedules::WhereNotIn('id', $schedule_ids)->get();`

答案 2 :(得分:0)

select 
    schedules . *,
    schedules.id as 'schedule_id',
    histories . *,
    histories.id as 'history_id'
from
    schedules
left join
    histories ON schedules.id = histories.schedule_id
        and schedules.template_id = histories.template_id
where
    histories.id IS NOT NULL
;

这列出了时间表ID 1& 2

select 
    schedules . *,
    schedules.id as 'schedule_id',
    histories . *,
    histories.id as 'history_id'
from
    schedules
left join
    histories ON schedules.id = histories.schedule_id
        and schedules.template_id = histories.template_id
where
    histories.id IS NULL
;

这列出了计划ID 3,但这与其他条件(例如

)不匹配
  • schedules.schedulable_id = 16

请参阅:http://sqlfiddle.com/#!2/28aad/21