【问题标题】:Selecting rows absent from one table against two other tables?选择一个表中缺少的行来对抗另外两个表?
【发布时间】:2014-09-09 01:48:46
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • 如果您想要没有相关历史记录的时间表,并且您正尝试使用反连接模式来获得它,它看起来像是在检查是否存在匹配的谓词 (@987654327 @) 应该在WHERE 子句中,而不是在外连接操作的ON 子句中。

标签: mysql sql laravel-4 eloquent


【解决方案1】:
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

【讨论】:

    【解决方案2】:

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

    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
    

    【讨论】:

    • Schedule ID 3 不在历史记录表中,所以它不应该出现在结果中吗?
    【解决方案3】:

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

    //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();`
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多