skip to Main Content

I have two queries, A and B. Query B can run only if i get the result from query A. But now i do both query separately. Below is my queries:

Query A

SELECT id, u_name, u_email, u_factory_id FROM wla_user WHERE email = '[email protected]'
id u_name u_email u_factory_id
1 John Bird [email protected] 8

Query B

SELECT id, door_details, con_details, factory_id FROM wla_container WHERE factory_id = $u_factory_id 
id door_details con_details factory_id
1 2 Tan car spareparts 8
1 3 Tan motorcycle spareparts 8
1 3 Tan kitchen 8

Now, i just want to make it with single query only. Can anyone know how to merge hat queries?

2

Answers


  1. Use a union query:

    SELECT id, u_name, u_email, u_factory_id
    FROM wla_user
    WHERE email = '[email protected]'
    UNION ALL
    SELECT id, door_details, con_details, factory_id
    FROM wla_container
    WHERE factory_id = $u_factory_id;
    
    Login or Signup to reply.
  2. According to the MySQL documentation, when you need the result from a query A for running the query B, you can use nested queries like so:

    Query

    SELECT id, door_details, con_details, factory_id 
    FROM wla_container 
    WHERE factory_id IN (
      SELECT u_factory_id 
      FROM wla_user 
      WHERE u_email = '[email protected]'
    );
    
    id door_details con_details factory_id
    1 2 Tan car spareparts 8
    2 3 Tan motorcycle spareparts 8
    3 3 Tan kitchen 8

    View on DB Fiddle

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search