Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL join subquery

I tried searching for an answer to my problem but failed to get an answer that actually helped. I've written an sql code but can't seem to find where the problem is. Is it possible to put a subquery in the "FROM" section?

SELECT S2.ITEM,
       S1.SHOP_ORDER,
       S1.OPERATION_NO,
       S1.START_DATE,
       S1.QTY_GOODS,
       S1.QTY_ENTERED,
       S1.QTY_MRB
FROM   (SELECT SHOP_ORD_RPT.OPERATION_NO,
               SHOP_ORD_RPT.SHOP_ORDER
        FROM   FLAME.SHOP_ORD_RPT
        WHERE  SHOP_ORD_RPT.OPERATION_NO = 110
                OR SHOP_ORD_RPT.OPERATION_NO = 370) AS S1
       JOIN (SELECT SHOP_ORD.SHOP_ORDER
             FROM   FLAME.SHOP_ORD
             WHERE  SHOP_ORD.ITEM = '3A2375'
                     OR SHOP_ORD.ITEM = '3A2703')AS S2
         ON S1.SHOP_ORDER = S2.SHOP_ORDER; 

The error I receive upon running the script is:

SQL command not properly ended

I'd appreciate if anyone can help. Thank you very much- Ruth

like image 365
user2764786 Avatar asked Sep 10 '13 12:09

user2764786


People also ask

Can you have joins in a subquery?

Use a join or a subquery anytime that you reference information from multiple tables. Joins and subqueries are often used together in the same query. In many cases, you can solve a data retrieval problem by using a join, a subquery, or both.

Which is faster subquery or join?

Advantages Of Joins: The retrieval time of the query using joins almost always will be faster than that of a subquery. By using joins, you can maximize the calculation burden on the database i.e., instead of multiple queries using one join query.

Which is better join or subquery in SQL Server?

I won't leave you in suspense, between Joins and Subqueries, joins tend to execute faster. In fact, query retrieval time using joins will almost always outperform one that employs a subquery. The reason is that joins mitigate the processing burden on the database by replacing multiple queries with one join query.

IS LEFT join faster than join?

If the tables involved in the join operation are too small, say they have less than 10 records and the tables do not possess sufficient indexes to cover the query, in that case, the Left Join is generally faster than Inner Join. As you can see above, both the queries have returned the same result set.


1 Answers

Try to remove AS keywrod after FROM and JOIN subquery as below

SELECT S2.ITEM, S1.SHOP_ORDER, S1.OPERATION_NO, S1.START_DATE,S1.QTY_GOODS, S1.QTY_ENTERED, S1.QTY_MRB
FROM (
    SELECT SHOP_ORD_RPT.OPERATION_NO, SHOP_ORD_RPT.SHOP_ORDER
    FROM FLAME.SHOP_ORD_RPT
    WHERE SHOP_ORD_RPT.OPERATION_NO =110
    OR SHOP_ORD_RPT.OPERATION_NO =370
    )  S1
JOIN (
    SELECT SHOP_ORD.SHOP_ORDER
    FROM FLAME.SHOP_ORD
    WHERE SHOP_ORD.ITEM ='3A2375'
    OR SHOP_ORD.ITEM ='3A2703'
    )  S2
ON S1.SHOP_ORDER = S2.SHOP_ORDER;
like image 111
Robert Avatar answered Sep 29 '22 11:09

Robert