简体   繁体   中英

selecting latest row of transaction table if row contains some values in MySql

These are my two tables, `Leadid` is Primary Key.


Table1 - (Master)   

    Leadid  Customer Name
    101     Ramesh Kumar
    102     Rajan Kumar
    103     Rahul Kumar

Table2 - (Transaction)

    id  Leadid  Followed_by
    1   101     SAKSHI
    2   101     MADHURI
    3   101     SAKSHI
    4   102     SAKSHI
    5   102     MADHURI
    6   103     SAKSHI
    7   103     SAKSHI

Question : I need all record from `Table1` and `Table2` , in which MAHURI has 
followed latest on Leadid. (As Below)

`102        Rajan Kumar     5   102     MADHURI`


In Case of SAKSHI it Should be:

101     Ramesh Kumar      3     101     SAKSHI
103     Rahul Kumar       7     103     SAKSHI

if same lead id is followed by others, previous transcation should not be included...

i e Leadid 101 was followed by madhuri also but then after followed by SAKSHI. 

so it should not be displayed when putting query for MADHURI.
// SAME CODE WHILE SELECT FOR SAKSHI


SELECT s.*,t.* FROM master s
INNER JOIN Transaction t
ON(t.leadid = s.leadid)
WHERE NOT EXISTS(SELECT 1 FROM Transaction tt
             WHERE t.leadid = tt.leadid
               AND t.id < tt.id)
 AND t.followed_by = 'SAKSHI'



// SAME CODE WHILE SELECT FOR MADHURI


SELECT s.*,t.* FROM master s
INNER JOIN Transaction t
ON(t.leadid = s.leadid)
WHERE NOT EXISTS(SELECT 1 FROM Transaction tt
             WHERE t.leadid = tt.leadid
               AND t.id < tt.id)
 AND t.followed_by = 'MADHURI'

http://sqlfiddle.com/#!9/a4fbb/39/0

http://sqlfiddle.com/#!9/a4fbb/38/0

选择leadid,customername,id,leadid,followedby from master a , transaction b where a.leadid= b.leadid and followby = 'MADHURI' order byleadid desc

This QUERY is used for getting latest value for 'MADHURI' only

SELECT a.*,b.* FROM `Master` AS a INNER JOIN `Transaction` AS b ON a.Leadid = b.Leadid WHERE Followed_by = "MADHURI" ORDER BY b.id DESC LIMIT 1; 

To use for all transction use the query

SELECT a.*,b.* FROM `Master` AS a INNER JOIN `Transaction` AS b ON a.Leadid = b.Leadid WHERE b.id = 'userid' ORDER BY b.id DESC LIMIT 1;  

change userid according to different users..

Select Master.*, Transaction.* from Master left join Transaction on Transaction.Leadid = Master.Leadid where Followed_by = "MADHURI" order by Transaction.Leadid desc limit 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM