Say, I have table named ‘member’
id name
===================
a John
b Frank
Member have ‘login_activities’
id login_time gol member
==========================================
1 2012-10-01 99 a
2 2012-10-01 125 b
3 2012-11-01 255 a
4 2012-11-02 111 b
5 2012-11-07 101 a
I want to create view that have information about when first time login and last time login of the members and also the ‘gol’ value only from the last login.
Is it possible?
I’ve tried many ways. One of my attempt:
CREATE VIEW view_firstlast
AS
SELECT
MIN(a.login_time) as first_login,
MAX(a.login_time) as last_login,
a.gol,
b.name
FROM
login_activities a
JOIN member b ON a.member = b.id
GROUP BY
a.member
It does’nt get right result. The ‘gol’ value is from the first login.
How to do this?
Something important here: MySQL doesn’t allow subquery in create view
You are ALMOST there. You have the login times, but I would take it and get the last login ID too to simplify a re-join to the login activities table vs trying to do a join on user AND date/time field since I would expect a key on the primary key of ID and not necessarily on (member, login_time) — however, for this query using the min/max on date grouped by member, I would DEFINITELY have an index on (member, login_time) for optimization.
Then, since the above works, but fails due to how MySQL implements views, you might need to do it with TWO views, such that
then another