2015-01-16 202 views
0

我需要一些幫助來加入下面的查詢,因爲我相信這是超級重的,while循環內其他while循環...一團糟,對吧?! :(Mysql複雜查詢加入

這工作,但如果有人可以幫助加入到只有一個查詢這樣的:

$query_1 = mysql_query("SELECT * FROM booking_reservation WHERE reservation_confirmed = '1' AND (reservation_name LIKE '$data%' OR reservation_phone LIKE '$data%' OR reservation_email LIKE '$data%')"); 

    while ($row = mysql_fetch_array($query_1)) { 
     $calendar_id = $row['calendar_id']; 
     $query_2 = mysql_query("SELECT * FROM booking_calendars WHERE calendar_id = '$calendar_id'"); 
     $row_2 = mysql_fetch_array($query_2); 
     $slot_id = $query_1['slot_id']; 
     $query_3 = mysql_query("SELECT * FROM booking_slots WHERE slot_id = '$slot_id'"); 
     while ($row_3 = mysql_fetch_array($query_3)) { 
      echo '<tr><td>' . htmlentities($row2['slot_date']) . '</td><td>' . htmlentities($query_3['slot_time_from']) . '</td><td>' . htmlentities($query_1['reservation_name']) . '</td><td>' . htmlentities($query_3['calendar_title']) . '</td><td>' . htmlentities($query_1['reservation_phone']) . '</td><td>' . htmlentities($query_1['reservation_email']) . '</td></tr>'; 
     } 
    } 
+1

停止使用不推薦使用的'mysql_ *'函數,改爲使用PDO/MySQLi。 – Raptor

+2

我認爲這可能是題外話題,因爲它屬於http://codereview.stackexchange.com/ – Pred

+0

這個問題似乎是主題(不幸)。 – RandomSeed

回答

0

其中一個應該是你想要的,你用INNER JOIN如果你想獲得該只存在預訂在booking_calendars和booking_slots,或LEFT JOIN如果你希望所有的保留,無論他們是否在其他表中不存在

內連接:

SELECT * FROM booking_reservation br 
INNER JOIN booking_calendars bc ON br.calendar_id=bc.calendar_id 
INNER JOIN booking_slots bs ON br.slot_id=bs.slot_id 
WHERE br.reservation_confirmed = '1' 
AND (br.reservation_name LIKE '$data%' 
OR br.reservation_phone LIKE '$data%' 
OR br.reservation_email LIKE '$data%') 

LEFT JOIN:

SELECT * FROM booking_reservation br 
LEFT JOIN booking_calendars bc ON br.calendar_id=bc.calendar_id 
LEFT JOIN booking_slots bs ON br.slot_id=bs.slot_id 
WHERE br.reservation_confirmed = '1' 
AND (br.reservation_name LIKE '$data%' 
OR br.reservation_phone LIKE '$data%' 
OR br.reservation_email LIKE '$data%') 

1重要提示,我們不建議使用SELECT *,它是更好地告訴你的mysql從每個表中需要哪些列,或從表中你從選擇。

注意:你應該聽什麼猛禽說,mysql_ *功能被取消,並將在以後的PHP版本中刪除,你應該開始使用PDOmysqli

+0

謝謝你們!它正在工作:) –

0

這種嘗試,我希望這個查詢作品對你來說

select * from booking_reservation br 
join booking_calendars bc ON br.calendar_id=bc.calendar_id 
join booking_slots bs ON bc.slot_id=bs.slot_id 
where br.reservation_confirmed='1' 
AND br.(reservation_name LIKE '$data%' OR br.reservation_phone LIKE '$data%' OR br.reservation_email LIKE '$data%') 
+1

逗號分隔的連接在二十多年前被標準SQL中的顯式連接取代。他們不應該再用了。 –

+0

@ Thorsten Kettner我希望你覺得快樂......其實在過去的查詢中,我沒有看到性能的差異......所以我去了查詢 –

+0

我很高興,謝謝你:-)這不是關於性能,但是;查詢是等同的。這是關於可讀性和錯誤傾向性(用逗號分隔的連接,例如,無法區分想要的和不想要的交叉連接)。 –