所以我试图将子查询的结果限制为每行一个
Tables:
Companies: id
Events: id, title, date
Relations: local_id, foreign_id
select `companies`.*, `e`.`title`
from `companies`
left join (
select `events`.*, `relations`.`local_id` as `pivot_local_id`, `relations`.`foreign_id` as `pivot_foreign_id`
from `events` inner join `relations` on `events`.`id` = `relations`.`foreign_id`
where `relations`.`local_id` = companies.id
order by `date` desc limit 1
) e on e.pivot_local_id = companies.id
此Q返回"#1054 - 未知列' companies.id'在' where子句"。
最后,我想取公司。*以及最新的活动标题' (如果有的话)每家公司。
如果可以通过Laravel 5.3的Eloquent ORM完成,我想知道更复杂的事情。
答案 0 :(得分:1)
表公司不可见/可用子查询,因此您有错误,主查询中存在的事实不够。
然后你必须加入子查询中的表公司,例如(我不知道子查询是否适合你的范围)
select `companies`.*, `e`.`title`
from `companies`
left join (
select `events`.*, `relations`.`local_id` as `pivot_local_id`, `relations`.`foreign_id` as `pivot_foreign_id`
from `events` inner join `relations` on `events`.`id` = `relations`.`foreign_id`
inner join companies on `relations`.`local_id` = companies.id
order by `date` desc limit 1
) e on e.pivot_local_id = companies.id
答案 1 :(得分:0)
所以,这是你的(不正确的)查询清理:
SELECT c.*, e.title
FROM companies c
LEFT JOIN (
SELECT ev.*, r.local_id AS pivot_local_id, r.foreign_id AS pivot_foreign_id
FROM events ev
INNER JOIN relations r on ev.id = r.foreign_id
WHERE r.local_id = c.id
ORDER BY `date` DESC LIMIT 1
) e ON e.pivot_local_id = c.id;
这(希望)应该是您打算实施的内容:
SELECT c.*, ev.title
FROM companies c
LEFT JOIN relations r ON c.id = r.local_id
LEFT JOIN events ev on ev.id = r.foreign_id
WHERE ev.title IS NOT NULL
ORDER BY `date` DESC LIMIT 1;
注意:您可能不需要WHERE ev.title IS NOT NULL
,并且应该将date
与表别名关联。