Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySql Inner Join with WHERE clause [closed]

Here is my code:

 SELECT table1.f_id  FROM table1 WHERE table1.f_com_id = '430' AND        table1.f_status = 'Submitted'   INNER JOIN table2  ON table2.f_id = table1.f_id  where table2.f_type = 'InProcess' 

I need information from table1 as all the id associated with f_com_id as 430 and status as submitted and the type should be only in process which is stored in other table(table2)

f_id is p_key and f_key in both the tables.
But this giving me errors, I think I am placing the WHERE clause wrong, how to fix it.?

Error msg: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INNER JOIN table2 ON table2.f_id = ' at line 2

like image 343
Aditya Kumar Avatar asked Sep 11 '12 07:09

Aditya Kumar


People also ask

Can we use inner join with WHERE clause?

To use the WHERE clause to perform the same join as you perform using the INNER JOIN syntax, enter both the join condition and the additional selection condition in the WHERE clause. The tables to be joined are listed in the FROM clause, separated by commas. This query returns the same output as the previous example.

Can I use join after WHERE clause?

You join two tables by creating a relationship in the WHERE clause between at least one column from one table and at least one column from another. The join creates a temporary composite table where each pair of rows (one from each table) that satisfies the join condition is linked to form a single row.

Can I use WHERE before inner join?

The where clause will be executed before the join so that it doesn't join unnecessary records. So your code is fine the way it is.

Is it better to filter in join or WHERE clause?

In terms of readability though, especially in complex queries that have multiple joins, it is easier to spot join conditions when they are placed in the ON clause and filter conditions when they are placed in the WHERE clause.


1 Answers

Yes you are right. You have placed WHERE clause wrong. You can only use one WHERE clause in single query so try AND for multiple conditions like this:

 SELECT table1.f_id  FROM table1     INNER JOIN table2      ON table2.f_id = table1.f_id  WHERE table2.f_type = 'InProcess'    AND f_com_id = '430'    AND f_status = 'Submitted'  
like image 192
Himanshu Jansari Avatar answered Oct 03 '22 10:10

Himanshu Jansari