11

我想编写如下所示的 SQL 查询。它的语法不正确。我该如何纠正?

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

4 回答 4

30

我认为在子选择之后缺少'as fp'。试试这个查询:

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
于 2012-04-05T07:29:31.833 回答
4

如果你加入一个子选择,你必须命名它。将名称放在子选择而不是其中的表上:

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
于 2012-04-05T07:31:23.993 回答
3

您没有为第二个表命名,但您稍后在 ON 子句中使用它。fp在右括号后丢失:

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"
;
于 2012-04-05T07:35:09.437 回答
1

尝试一个没有嵌套 SELECT 语句的 JOIN,只有一个表名。尝试:

$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";
于 2012-04-05T07:33:16.333 回答