2012-04-05 140 views
6

我想編寫如下的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"; 

回答

18

我覺得在子選擇之後缺少'作爲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 
+0

Thanks Adrin,This works fine, – user1157690 2012-04-05 07:31:49

3

如果你加入一個子選擇,你必須命名它。將名稱放在子選擇而不是表格裏面:

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 
0

嘗試一個沒有嵌套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"; 
1

你沒有第二表來給出一個名字,但你在接通後條款使用它。 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" 
;