JetPro
JetPro

Reputation: 1054

LEFT OUTER JOIN with a WHERE clause on the first table

I want to SELECT a some rows from a table, but these rows must satisfy a condition like column = value. Here's my SELECT statement:

$query = "SELECT t1.title, t1.introtext, t2.jr_street, t2.jr_city, 
    t2.jr_state, t2.jr_postalcode, t2.jr_country, t3.created, t3.name, 
    t3.title, t3.comments, t4.ave 
FROM $table1 t1
    LEFT OUTER JOIN $table2 t2 ON t1.id = t2.contentid
    LEFT OUTER JOIN $table3 t3 ON t1.id = t3.pid
    LEFT OUTER JOIN $table4 t4 ON t1.id = t4.reviewid
";

I tried adding a WHERE clause after the FROM statement, but I am getting an SQL syntax error.

Upvotes: 0

Views: 831

Answers (1)

Karl Lorey
Karl Lorey

Reputation: 1616

Seems like I have to guess your problem. Next time you should give us your full example a the exact error. Did you try something like this?

$value = (int) $_POST['value'];
$query = "SELECT t1.title, t1.introtext, t2.jr_street, t2.jr_city, t2.jr_state,
t2.jr_postalcode, t2.jr_country, t3.created, t3.name, t3.title, 
t3.comments, t4.ave FROM $table1 t1
LEFT OUTER JOIN $table2 t2 ON t1.id = t2.contentid
LEFT OUTER JOIN $table3 t3 ON t1.id = t3.pid
LEFT OUTER JOIN $table4 t4 ON t1.id = t4.reviewid
WHERE t2.column = ".$value."
AND t1.catid=8";

I just guessed you want to select from table2 ;) You have to fill in the right table and column. Also i put the category selection in the where clause since imho this makes it more readable.

Please make absolutely sure that all variables like $value (and the tables) are save for usage in a query, for example that $value is an integer and the tables are explicitly set in your code and are not a user input. You can read more about SQL-Injections here:

Upvotes: 1

Related Questions