I have some MS Access 2010 link tables
that links back to the first table, like so:
Item LinkTable
[ ID ] [ ID ]
[ ItemName ]-1-------*-[ FromItem ]
[ ]-1-------*-[ ToItem ]
Fig.1: FromItem
and ToItem
references 'Item.ID'
I would like to make a query that links together all three tables and display for example the follwoing fields
(from)Item.ItemName | LinkTable.ID | (to)Item.ItemName
I have tried the following SQL, but it complains about the second occurence of Item, with a message "Can't repeat table name "Item" in the FROM clause" in the expression "Item LEFT JOIN LinkTable" below:
SELECT *
FROM Item LEFT JOIN
(
Item LEFT JOIN LinkTable ON (LinkTable.ToItem =Item.ID)
)
ON (LinkTable.FromItem = Item.ID);
Q1: Why can't I link back to the "starting table" like this without causing an error message?
Q2: How should I define the Select fields in order to show both the from-ItemName and the to-ItemName without confusing them? (In the example I wrote "Select *" to simplify)
// Rolf
Edit:______________________________________________________
Based on the reply by @Andomar (below) I ended up with the following working code. I used INNER JOIN
instead of LEFT JOIN
in order to get only matching Items
:
SELECT fro.ItemName
, lt.ID
, to.ItemName
FROM Item fro
INNER JOIN (LinkTable lt
INNER JOIN Item to ON lt.toItem = to.ID)
ON fro.ID = lt.fromItem;
You can alias a table name. For example, this aliases the table Item
to the alias i1
:
FROM Item i1
You can now use the same table again and use a different alias to identify it. Combining this with the parenthesis Access requires for multiple joins, you get:
SELECT i1.ItemName
, i2.ItemName
FROM (Item i1
LEFT JOIN LinkTable lt ON lt.FromItem = i1.ID)
LEFT JOIN item i2 ON i2.ID = lt.ToItem