简体   繁体   中英

Select from 3 joined tables with condition?

I have four tables:

request:

id----salesid--custid---serial-----active
=======================================
1-------2-------1--------13221-------1
2-------1-------2--------15422-------1
3-------1-------3--------11233-------1
4-------2-------1--------11342-------1

salesid is foreign key from emp table and we don't need any thing from employee table except the emp id so its not important to show its details

custid is foreign key of customer id

serial is the serial of that request

active is flag for delete

requestcondition:

id-----requestid-----requestcondition 
======================================
1--------1-------------pending
2--------1-------------installation pending 
3--------2-------------pending  
4--------1-------------completed

and

customer:

id------name
============
1-------aaaa
2-------bbbb
3-------cccc

I want to select last condition added for specific request and the name of the customer and request serial according to the salesid column

Try

SELECT Id=scope_identity();

Or

LAST_INSERT_ID();

Through this you can get the last inserted Id and after getting last condition, Implement joins.Read about it on this Link .

    select r.id, rc.id, c.name, r.serial, rc.requestcondition
    from request r
    inner join customer c on c.id=r.custid
    inner join requestcondition rc on rc.requestid=r.id
    inner join (
       select max(id) as rcid
        from requestcondition
        group by requestid
    ) latest on latest.rcid=rc.id

This will give the latest status of all requests. If you need just the latest status for one request, you would need to add a where clause at the end.

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