Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query for Inner Join with Select

Tags:

sql

I want to write a SQL query like the following. Its syntax is not correct. How can I correct it?

$sql_package_feature = "SELECT f.feature_id, f.feature_name FROM  tbl_feature f 
LEFT JOIN SELECT * FROM tbl_feature_and_profile fp WHERE fp.profile_id= ? ) ON 
f.feature_id = fp.feature_id AND f.package_id = fp.package_id WHERE fp.feature_id 
IS NULL  AND f.package_id = ? ORDER BY f.feature_id";
like image 404
user1157690 Avatar asked Apr 05 '12 07:04

user1157690


People also ask

What is inner join query in SQL?

Inner Join clause in SQL Server creates a new table (not physical) by combining rows that have matching values in two or more tables. This join is based on a logical relationship (or a common field) between the tables and is used to retrieve data that appears in both tables.

Can I use WHERE clause in inner join?

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.

Can we use and with inner join in SQL?

With the AND in the inner join you can specify it even more. Join the tables on the columns, where A1. Column = 'TASK' and throw away the rest. You could just as easily move the AND to the WHERE -Clause.


2 Answers

I think it was abount missing 'as fp' after subselect. Try this query:

SELECT 
      f.feature_id, 
      f.feature_name 
FROM  tbl_feature f 
LEFT JOIN (SELECT * FROM tbl_feature_and_profile fp WHERE fp.profile_id= ? ) 
     as fp ON (f.feature_id = fp.feature_id AND f.package_id = fp.package_id) 
WHERE 
     fp.feature_id IS NULL  AND f.package_id = ? ORDER BY f.feature_id
like image 90
Adrian Serafin Avatar answered Sep 25 '22 15:09

Adrian Serafin


If you join against a subselect, you have to name it. Put the name on the subselect instead of the table inside it:

SELECT f.feature_id, f.feature_name
FROM  tbl_feature f
LEFT JOIN (
  SELECT *
  FROM tbl_feature_and_profile
  WHERE profile_id= ?
) fp ON f.feature_id = fp.feature_id AND f.package_id = fp.package_id
WHERE fp.feature_id IS NULL AND f.package_id = ?
ORDER BY f.feature_id
like image 38
Guffa Avatar answered Sep 25 '22 15:09

Guffa