0

我有桌子:

用户

id | first_name | last_name
 1   Johnny       Steve
 2   Kim          Borden

销售量

id | user_id | service_id | date
 1    1         2           2012-02-12
 2    1         6           2012-04-21

我想检索附有最近销售信息的用户列表。如果没有找到,则为 NULL。

到目前为止我所拥有的:

SELECT
    users.*,
    sales.*,
FROM
    users
LEFT JOIN
    sales ON users.id=sales.user_id

但这为约翰尼创造了两项记录,因为这两项是销售额。有任何想法吗?

4

4 回答 4

0

Without the use of analytic functions, this is a pretty basic way to do what you're trying to do:

select users.*, sales.*
from users, 
(select a.*
    from sales a,
        (select user_id, MAX(date) as mostRecentDate
        from sales
        group by user_id) b
    where a.user_id = b.user_id
      and a.date = b.mostRecentDate) sales
where users.id = sales.user_id;

I don't have a mysql server available to me at the moment to test this, if it gives any errors, just post back.

于 2012-07-23T21:47:55.653 回答
0
SELECT 
        u.*,
        SUBSTRING_INDEX(GROUP_CONCAT(s.id ORDER BY s.date DESC,s.id DESC),',',1) as sale_id,
        SUBSTRING_INDEX(GROUP_CONCAT(s.service_id ORDER BY s.date DESC,s.id DESC),',',1) as service_id,
        SUBSTRING_INDEX(GROUP_CONCAT(s.date ORDER BY s.date DESC,s.id DESC),',',1) as sale_date
FROM users u 
LEFT JOIN sales s ON s.user_id = u.id
GROUP BY u.id;

这是您在没有时间的情况下最接近“最后一次销售”的方式

于 2012-07-23T21:40:42.583 回答
0

SELECT u.id as id, u.first_name as first_name, u.last_name as last_name, MAX(s.date) as date FROM users as u LEFT JOIN sales as s on u.id = s.user_id GROUP BY id

查看此链接以获取更复杂的每组查询结构类型的前 N ​​个。

http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/

于 2012-07-23T21:34:23.747 回答
0
    SELECT u.*, s.*,
    FROM users u
    LEFT JOIN 
(select max(id) as sales_id, user_id from sales group by user_id) sa 
on sa.user_id = u.id
    LEFT JOIN sales s ON sa.user_id=s.user_id and s.id=sa.sales_id

编辑:如果您将日期设置为 TIMESTAMP,则可以在 MAX() 中使用它而不是 id。如果您保留它作为日期,您仍然可以使用它,但是您将获得额外的记录,以防一天内有多个用户销售

于 2012-07-23T21:42:40.427 回答