如果行包含MySql中的某些值,则选择事务表的最新行

时间:2016-03-07 06:06:43

标签: php mysql sql-server join

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.

4 个答案:

答案 0 :(得分:0)

// 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

答案 1 :(得分:-1)

选择leadid,customername,id,leadid,后跟来自master a,事务b,其中a.leadid = b.leadid,followby ='MADHURI'order by leadid desc

答案 2 :(得分:-1)

此QUERY仅用于获取'MADHURI'的最新值

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; 

要用于所有转换,请使用查询

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;  

根据不同的用户更改用户ID ..

答案 3 :(得分:-2)

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