[英]Selecting rows absent from one table against two other tables?
I have three tables I am trying to build a query against in Eloquent to get only the rows from two tables that are absent from a third table. 我试图在Eloquent中构建一个针对三个表的查询,以仅从两个表中获取第三行中不存在的行。
One is the table histories
which references the other two tables schedules
and templates
. 一种是表的histories
,其中引用了另外两个表的schedules
和templates
。 If there is a template schedule history, I don't want to get that schedule. 如果有模板时间表历史记录,我不想获取该时间表。
Normally I would expect this could be done using a LEFT JOIN
on the third table where the id IS NULL
but this doesn't work in this instance. 通常,我希望可以在id为IS NULL
的第三个表上使用LEFT JOIN
来完成此操作,但在这种情况下不起作用。 Every query I have tried thus far always returns the null columns along with the row I don't want. 到目前为止,我尝试过的每个查询总是返回空列以及不想要的行。
Here is a fiddle with the relevant schema and an example query: http://sqlfiddle.com/#!2/28aad/5 这是有关模式和示例查询的小提琴: http : //sqlfiddle.com/#!2/28aad/5
How can I structure my query to get the results desired? 如何构造查询以获得所需的结果?
Your query should look like this: However your query is not returning any results because each schedule/template has a history record. 您的查询应如下所示:但是您的查询不会返回任何结果,因为每个计划/模板都有一个历史记录。
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
Assuming you wish to get rows for schedules
table which are not in histories
table, your eloquent query would be such: 假设您希望获取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();`
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
;
This lists schedules IDs 1 & 2 此列表列出了计划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
;
This lists schedule ID 3 , but this does not match other conditions such as 该列表列出了计划ID 3,但与其他条件不匹配,例如
see: http://sqlfiddle.com/#!2/28aad/21 参见: http : //sqlfiddle.com/#!2/28aad/21
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.