3

I normally do a join like this:

$query = "SELECT table1.ColA, table2.ColC ".
     "FROM table1, table2".
        "WHERE table1.uid = table2.uid";

But in this case the WHERE portion is already used to specify a record using a PHP variable. How do I JOIN table 2 in this case?

SELECT SQL_CALC_FOUND_ROWS ColA, ColB FROM Table1 WHERE value = $value
Mahmoud Gamal
  • 78,257
  • 17
  • 139
  • 164
Optional Name
  • 47
  • 1
  • 2
  • 6
  • `$sql = 'select * from table1, table2 where table1.uid = table2.uid and value = \''.$value.'\'';` should work if I correctly understood your question. – Leri Nov 29 '12 at 11:39
  • 1
    See also [this question](http://stackoverflow.com/questions/354070/sql-join-where-clause-vs-on-clause). It is usually more readable to use the `JOIN` clause to specify join conditions. – DCoder Nov 29 '12 at 11:41

3 Answers3

4

They are already joined. It is the same as

SELECT table1.ColA, table2.ColC 
FROM table1
INNER JOIN table2 ON  table1.uid = table2.uid

If you need to add more conditions, add them to the WHERE clause:

SELECT table1.ColA, table2.ColC
FROM table1, table2
WHERE table1.uid = table2.uid
  AND value = $value;

Or, with the ANSI SQL-92 syntax:

SELECT table1.ColA, table2.ColC 
FROM table1
INNER JOIN table2 ON  table1.uid = table2.uid
WHERE  value = $value;

Note that: You should always use the later syntax, with JOIN to join the tables instaed of the WHERE clause. It is the recommended way to do this. See this post for more information.

Community
  • 1
  • 1
Mahmoud Gamal
  • 78,257
  • 17
  • 139
  • 164
1

Try this ::

SELECT 
SQL_CALC_FOUND_ROWS ColA, 
ColB 

FROM table1, table2
WHERE value = $value 
and table1.uid = table2.uid

OR YOU CAN JOIN THE TABLES THROUGH

SELECT 
SQL_CALC_FOUND_ROWS ColA, 
ColB 

FROM table1 INNER JOIN table2 on table1.uid = table2.uid
WHERE value = $value 
Sashi Kant
  • 13,277
  • 9
  • 44
  • 71
1

Please try this

$query = "SELECT table1.ColA, table2.ColC FROM table1, 
            table2 WHERE table1.uid = table2.uid and table1.value=$value";

OR

$query = "SELECT table1.ColA, table2.ColC FROM table1 INNER JOIN table2 
               ON (table1.uid = table2.uid) WHERE table1.value=$value";
Elby
  • 1,624
  • 3
  • 23
  • 42