简体   繁体   English

3 个表的限价/订单结果

[英]Limit/order result with 3 tables

So I'm trying to limit the result of the subquery to one per row所以我试图将子查询的结果限制为每行一个

    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

This Q returns "#1054 - Unknown column 'companies.id' in 'where clause".这个 Q 返回“#1054 - 'where 子句中的未知列'companys.id'”。

In the end I want to fetch company.* and 'the latest event title' (if there are any) for each company.最后,我想为每个公司获取 company.* 和“最新事件标题”(如果有的话)。

To further complicate things I would love to know if this can be accomplished with Laravel 5.3's Eloquent ORM.更复杂的是,我很想知道这是否可以通过 Laravel 5.3 的 Eloquent ORM 来完成。

The table companies is not visible/available is subquery so you have the error the fact that is present in main query don't is enough.表公司不可见/可用是子查询,因此您有错误,主查询中存在的事实不够。

Then you must join the table companies inside the subquery eg (I don't know if the subquery is right for your scope)然后你必须在子查询中加入表公司,例如(我不知道子查询是否适合你的范围)

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

So, this is your (incorrect) query cleaned up:所以,这是您清理的(不正确的)查询:

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;

And this (hopefully) should be what you're intending to implement:这(希望)应该是您打算实施的:

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;

Notes: you probably don't need the WHERE ev.title IS NOT NULL , and you should associate date to a table alias.注意:您可能不需要WHERE ev.title IS NOT NULL ,您应该将date与表别名相关联。

Good luck!祝你好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM