mysql - How can I get the latest two dates from a single column, in a single table, for two separate results of a WHERE clause? -
i have query returns 5 columns.
one of columns shows latest date value row 1 column contains either string "seller-contact" or "buyer-contact".
the original code works fine, , looks this.
select trim(p.title) `property address`, trim(us.name) `staff`, date_format(from_unixtime(max( n.datecreated)), '%d-%m-%y') `last contact note`, datediff( date_format(from_unixtime(unix_timestamp(now())), '%y-%m-%d'), date_format(from_unixtime(max(n.datecreated)), '%y-%m-%d') ) `days since last note` ias_property `p` left join ias_note_stream `ns` on ns.target_id = p.id left join ias_note `n` on ns.note_id = n.id left join ias_user_staff `us` on p.user_staff_id = us.id p.status = 'sold' , p.isarchived = 0 , us.position = 'sp' , (n.data '%buyer-contact%' or n.data '%seller-contact%') group p.id order max(n.datecreated) asc
i tried achieve above using 2 subqueries each result. not fail or result in error codes. on larger, live, database takes far long (returning 270 rows, i'm assuming sub-query's makes 270^270x time take previously; never finishes hangs).
select trim(p.title) `property address`, trim(us.name) `staff`, (select date_format(from_unixtime(max(n.datecreated)), '%d-%m-%y') ias_property `p` left join ias_note_stream `ns` on ns.target_id = p.id left join ias_note `n` on ns.note_id = n.id n.data '%buyer-contact%' , p.status = 'sold' , p.isarchived = 0 , us.position = 'sp' ) `last buyer contact note`, (select date_format(from_unixtime(max(n.datecreated)), '%d-%m-%y') ias_property `p` left join ias_note_stream `ns` on ns.target_id = p.id left join ias_note `n` on ns.note_id = n.id n.data '%seller-contact%' , p.status = 'sold' , p.isarchived = 0 , us.position = 'sp' ) `last seller contact note`, datediff( date_format(from_unixtime(unix_timestamp(now())), '%y-%m-%d'), date_format(from_unixtime(max(n.datecreated)), '%y-%m-%d') ) `days since last note` ias_property `p` left join ias_note_stream `ns` on ns.target_id = p.id left join ias_note `n` on ns.note_id = n.id left join ias_user_staff `us` on p.user_staff_id = us.id p.status = 'sold' , p.isarchived = 0 , us.position = 'sp' , (n.data '%buyer-contact%' or n.data '%seller-contact%') group p.id order max(n.datecreated) asc
is there way make simpler can have like
date_format(from_unixtime(max( n.datecreated n.data '%seller-%' )), '%d-%m-%y') `last buyer contact note;
tldr: how display both results of clause same column 2 separate columns (as a
, b
) etc?
you can put if
inside max function max of values.
date_format(from_unixtime(max(if(n.data '%buyer-contact%',n.datecreated,null))), '%d-%m-%y') `last buyer contact note` date_format(from_unixtime(max(if(n.data '%seller-contact%',n.datecreated,null))), '%d-%m-%y') `last seller contact note`
adding these should not affect performance of original query.
Comments
Post a Comment