2013-02-20 35 views
0

使用左加入筛选查询与秩序和限制使用左的连接时

store_profile 
id + store_name 
1 | Accessorize.me 
2 | Active IT 
3 | Edushop 
4 | Gift2Kids 
5 | Heavyarm 
6 | Bamboo 

store_fee 
id + store_id + date_end 
1 | 1  | 27-6-2013 
2 | 2  | 29-8-2013 
3 | 3  | 02-6-2013 
4 | 4  | 20-4-2013 
5 | 4  | 01-7-2013 
6 | 4  | 28-9-2013 
7 | 5  | 03-9-2013 
8 | 6  | 01-9-2013 

我以前的查询

$order_by_for_sort_column = "order by $column" //sorting column 

$query = "SELECT * FROM store_profile sp LEFT JOIN store_fee sf ON (sf.store_id = sp.id) $order_by_for_sort_column"; 

我要的是order by id desclimit 1时如何使用order bylimit筛选查询对于表store_fee不适用于整个查询。所以我可以为每个商店获取date_end的最新日期。

正如你所看到的store_id 4(store_fee)我有3个不同的日期,我只想抓住最新的日期。

,结果应该是这样的

1 | Accessorize.me 27-6-2013 
2 | Active IT  29-8-2013 
3 | Edushop   02-6-2013 
4 | Gift2Kids  28-9-2013 
5 | Heavyarm  03-9-2013 
6 | Bamboo   01-9-2013 

回答

1
SELECT a.id, a.store_name, MAX(b.date_End) date_end 
FROM store_profile a 
     LEFT JOIN store_fee b 
      ON a.ID = b.store_ID 
GROUP BY a.id, a.store_name 

但如果数据类型date_End列是VARCHAR,上面的查询不会工作,因为它排序每个字符的价值和它可能会错误地给出不希望的结果。 18-1-2013大于01-6-2013

为了进一步获得更多的知识有关加入,请访问以下链接:

+0

数据类型是 “日期” – rusly 2013-02-20 08:36:10

+0

@rusly那么查询工作正常': D' – 2013-02-20 08:36:58

+0

您认为'store_profile.store_name'是唯一的,并将其用作关键字。这可能是错误的假设,并且将业务领域用作关键字,即使它们是独特的,无论如何都是不好的做法。 – 2013-02-20 08:37:49

1
SELECT * 
FROM store_profile AS sp 
    LEFT JOIN (
    SELECT store_id, MAX(date_end) 
    FROM store_fee 
    GROUP BY store_id 
) AS sf 
    ON sp.id=sf.store_id;