简体   繁体   中英

SQL query for Inner Join with Select

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";

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

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

You didn't give a name to the second table, but you are using it later in the ON-Clause. fp was missing after the closing bracket:

SELECT f.feature_id, f.feature_name 
FROM  tbl_feature f
LEFT JOIN (
    SELECT *
    FROM tbl_feature_and_profile fp 
    WHERE fp.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"
;

Try a JOIN without a nested SELECT statement, only a table name. Try:

$sql_package_feature = 
"SELECT f.feature_id, f.feature_name 
FROM  
tbl_feature f 
LEFT JOIN 
tbl_feature_and_profile fb
ON f.feature_id = fp.feature_id AND f.package_id = fp.package_id 
WHERE fp.feature_id IS NULL  AND f.package_id = ? AND fp.profile_id = ? ORDER BY f.feature_id";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM