2009-10-15 53 views
0
SELECT * FROM a 
JOIN (SELECT * FROM b WHERE b.aId = a.Id) AS c ON c.aId = a.Id 

它说不承认:a.Id在Where子句中。在加入表格时不承认列在哪里条款

我知道它可能导致即时通讯使用临时表和a.Id不能通过,但有什么办法可以做到这一点?

因为这里到底发生了什么

SELECT * 
    FROM a 
    JOIN (SELECT * FROM b 
     WHERE b.aId = a.Id 
     ORDER BY b.dateReg DESC 
     LIMIT 1) AS c ON c.aId = a.Id 

我需要ORDER BY b.dateReg DESC LIMIT 1,因为它返回我的最后一行用一个表assosiates ..如果你需要我可以张贴创建查询

回答

2

- 基于b

select * from b x 
where exists(
    select id 
    from b y 
    where y.id = b.id 
    having max(y.dateReg) = x.dateReg 
    group by id 
    ) 

找到最后行 - 然后加入该b到A,这是最后的查询:

select * from a 
join 
(
    select * from b x 
    where exists(
     select id 
     from b y 
     where y.id = b.id 
     having max(y.dateReg) = x.dateReg 
     group by id 
     ) 

) as last_rows on last_rows.id = a.id 

- 简单:

select * 
from a join b x on a.id = x.id 
where exists(
    select id 
    from b y 
    where y.id = b.id 
    having max(y.dateReg) = x.dateReg 
    group by id) 

- 或者,如果你会使用的Postgres:

select DISTINCT ON (a.id) * 
from a join b x on a.id = x.id 
order by a.id, b.dateReg DESC 
-- look ma! no group by!  

-- nothing beats postgresql's simplicity :-) 
+0

你看我确实有查询工作,它是返回行的螺旋负载...我希望我们能做到这一点,所以它只返回最后..我们可以限制它 – 2009-10-15 03:48:15

+0

如果有我接受你的没有别人 – 2009-10-15 03:54:23

+0

是的,我看到第一个代码不工作,我急着吃午饭。我现在编辑它,我认为更正的代码是正确的 – 2009-10-15 04:40:26

1

尝试:

SELECT DISTINCT * 
    FROM A 
    JOIN B b ON b.aid = a.id 
    JOIN (SELECT b.aid, 
       MAX(b.datereg) 'max_datereg' 
      FROM B b 
     GROUP BY b.aid) md ON md.aid = b.aid 
         AND md.max_datereg = b.datereg 

如果你想第一个记录与该员工关联,使用:

SELECT DISTINCT * 
    FROM A 
    JOIN B b ON b.aid = a.id 
    JOIN (SELECT b.aid, 
       MIN(b.datereg) 'min_datereg' 
      FROM B b 
     GROUP BY b.aid) md ON md.aid = b.aid 
         AND md.min_datereg = b.datereg