2014-02-22 65 views
0

PHP PDO查詢兩個表我有這個疑問在同一查詢

$sth = $db->prepare(
    'SELECT shout_id FROM shout_info' 
    . ' WHERE shout_location = "3"' 
    . ' AND (shout_sex = "0" OR shout_sex = ?)' 
    . ' AND (shout_age = "0" OR shout_age = ?)' 
    . ' AND shout_location_spec = ? AND user_id <> ?' 
    . ' ORDER BY date_created DESC LIMIT 15' 
); 

     $sth->bindValue(1, $user_sex); 
     $sth->bindValue(2, $sql_general_age); 
     $sth->bindValue(3, $user_workplace); 
     $sth->bindValue(4, $user_id); 
     $sth->execute(); 
     $workplace_array = $sth->fetchAll(PDO::FETCH_ASSOC); 

它很長,但我不知道如何我也能做到從一列中的復另一個表檢查將AND shout_approved = "1"但shout_approved在表shout_status中,shout_status的主ID是shout_id,就像在shout_info中一樣,所以我不確定如何使用與在原始查詢中檢查的相同ID來檢查此表。 對不起,我試圖儘可能清楚地解釋。

讓我知道,如果你有什麼事

回答

1

您將需要這個LEFT OUTER JOIN

SELECT 
    s.shout_id 
FROM 
    shout_info s 
     LEFT OUTER JOIN 
      shout_status ss 
     ON 
      ss.shout_id = s.shout_id 
WHERE 
    s.shout_location = "3" AND 
    (s.shout_sex = "0" OR s.shout_sex = ?) AND 
    (s.shout_age = "0" OR s.shout_age = ?) AND 
    s.shout_location_spec = ? AND 
    s.user_id <> ? AND 
    ss.shout_approved = "1" 
ORDER BY 
    s.date_created DESC 
LIMIT 
    15 
+0

運行完美,非常感謝 – Arken

+0

沒問題, 祝你好運! – MonkeyZeus

0

這應該工作:

SELECT 
shout_id 
FROM 
shout_info 
WHERE shout_location = "3" 
AND (shout_sex = "0" OR shout_sex = ?) 
AND (shout_age = "0" OR shout_age = ?) 
AND shout_location_spec = ? AND user_id <> ? 
ORDER BY date_created DESC LIMIT 15' 
Join shout_approved on shout_approved.shout_id = shout_id 
where shout_approved = "1" 
+0

儘管您的查詢可能有效,但您應該始終使用顯式JOIN,否則DBMS必須執行更多的查找工作,以確定您所暗含的JOIN類型,並且可以輕鬆地按指數方式增加查詢時間。 – MonkeyZeus