views:

131

answers:

2

I am new to SQL, and have two tables that hold data(I am using Adodb). They both have keys that connect them together, so I wanted to select a name from the first table if that has a parent id in the second table. I am using:

$db->GetCol("SELECT x_ast.name FROM x_ast, x_ast_tree WHERE x_ast_tree.parent='$parent_id'");

This returns an array with the correct data, but it is in there twice. (I assume because I asked it to come from two tables):

Array
(
    [0] => Trash
    [1] => Users
    [2] => admin
    [3] => Trash
    [4] => Users
    [5] => admin
)

How can I select a field from one table based on the data in another table, but only return one set of results? What am I doing wrong?

+1  A: 

The problem is that you haven't set a criterion for joining the two tables, so it's doing a cross join.

SELECT x_ast.name
FROM x_ast
INNER JOIN x_ast_tree
  ON x_ast.somefield=x_ast_tree.somefield
WHERE x_ast_tree.parent='$parent_id'
Ignacio Vazquez-Abrams
Beautiful, that worked! I knew about join, just did not understand them yet. Thank you!
Nic Hubbard
A: 

Have a look at Joins Between Tables

astander