简体   繁体   中英

Value of where clause in sql query is the parent column of select

I have a query like below. As shown it has a subquery. What I want is to make the value of where clause should be base on the s1.id . Currently I make it static 2 because I've tried where s2.id = s1.id and it's not work:

SELECT 
s1.id,
s1.code,
(SELECT 
        c.company_name
    FROM
        company c
            INNER JOIN
        (SELECT 
            a.company_id
        FROM
            agent a
        INNER JOIN shop s2 ON a.id = s2.agent_id
        WHERE
            s2.id = 2) AS agent_shop ON agent_shop.company_id = c.id) AS agent_company_name
FROM
     shop s1

Is there a way to achieve it?

I believe this could be done with a simple join instead:

select
shop.id,
shop.code,
company.company_name as agent_company_name
from
shop
left join agent on shop.agent_id=agent.id
left join company on agent.company_id=company.id
where
shop.id=2;

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