Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use subquery in join condition in Access?

In postgresql I can use subquery in join condition

SELECT * 
FROM table1 LEFT JOIN table2
     ON table1.id1 = (SELECT id2 FROM table2 LIMIT 1);

But when I try to use it in Access

SELECT *
FROM table1 LEFT JOIN table2 
     ON table1.id1 = (SELECT TOP 1 id2 FROM table2);

I get syntax error. Is it actually impossible in Access or just my mistake?

I know that I can get the same result with WHERE, but my question is about possibilities of JOIN in Access.

like image 489
Nelson Tatius Avatar asked Nov 26 '12 15:11

Nelson Tatius


People also ask

Can we use subquery in JOIN condition?

Subqueries can be used as an alternative to joins.

Can we replace subquery with JOIN?

However, in some cases a subquery can be replaced with a more efficient JOIN. If you can avoid a subquery and replace it with a JOIN clause, you should do so without hesitation. But of course, in some cases, using a subquery is the only way to solve a data question.

Is it possible to JOIN two or more tables data using subqueries?

Although joining tables together is probably the most common way of working with multiple tables, you can often achieve the same results through use of a subquery.

Can we use select statement in JOIN?

So, an SQL Join clause in a Select statement combines columns from one or more tables in a relational database and returns a set of data. The From is also an essential part of the Select statement and this is where it's specified which table we're pulling data from.


1 Answers

It's not possible, per the MSDN documentation:

Syntax

FROM table1 [ LEFT | RIGHT ] JOIN table2 ON table1.field1 compopr table2.field2

And (emphasis mine):

field1, field2: The names of the fields that are joined. The fields must be of the same data type and contain the same kind of data, but they do not need to have the same name.

It appears you can't even have hard-coded values in your join; you must specify the column name to join against.

In your case, you would want:

SELECT *
FROM Table1
LEFT JOIN (
    SELECT DISTINCT TOP 1 ID 
    FROM Table2
    ORDER BY ID
) Table2Derived ON Table1.ID = Table2Derived.ID
like image 151
LittleBobbyTables - Au Revoir Avatar answered Oct 07 '22 04:10

LittleBobbyTables - Au Revoir