使用Select进行内部连接的SQL查询

时间:2012-04-05 07:27:15

标签: sql

我想编写如下的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 个答案:

答案 0 :(得分:22)

我认为这是在subselect之后错过'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

答案 1 :(得分:3)

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

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

答案 2 :(得分:2)

您没有为第二个表提供名称,但您稍后在ON-Clause中使用它。结束括号后遗失了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"
;

答案 3 :(得分: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";