3

I am trying to join 3 tables together but I keep getting 'unknown table 'calls' in field list. I know the table 'calls' exists

This works...

$sql = "SELECT * FROM calls WHERE id = '$diary_id'";

but this doesn't...

$sql = "SELECT * FROM (SELECT calls.id AS calls_id, calls.assigned_user_id AS assigned_user) calls
RIGHT JOIN accounts on accounts.parent_id = accounts.id
LEFT JOIN users on assigned_user = user.id
WHERE calls_id = '$diary_id'";

I am trying to use aliases because the tables I am trying to join have the same field names (an inherited database I have to use).

Any help will be greatly appreciated

tatty27
  • 1,553
  • 4
  • 34
  • 73

1 Answers1

7

Your subquery:

SELECT calls.id AS calls_id, calls.assigned_user_id AS assigned_user

is selecting calls.id and calls.assigned_user but there is no FROM clause from which the calls table/alias is defined. Add FROM calls to the subquery (although why use a subquery here at all?).

You're also referring to user.id in your join criterion, but the table is called users.

And your join criterion for the accounts table, accounts.parent_id = accounts.id, looks very suspect: it appears that you're trying to traverse hierarchical data that has been stored using the adjacency list model, but this join won't accomplish that; indeed, MySQL doesn't support recursive functions—so it is not well suited to this model at all. You might consider restructuring your data to use either nested sets or closure tables. See this answer for more information.

Instead:

SELECT *
FROM   calls
  RIGHT JOIN accounts ON accounts.parent_id  = accounts.id -- is this right?
   LEFT JOIN users    ON calls.assigned_user = user.id
WHERE calls.id = '$diary_id'
Community
  • 1
  • 1
eggyal
  • 122,705
  • 18
  • 212
  • 237
  • you're correct when yu say accounts.parent_id looks a bit dodgy, it should be calls.parent_id = account.id. I'd been looking at this for several hours and had rewritten it many times because I was missing the from clause, doh – tatty27 Aug 31 '12 at 20:42