2011-10-18 26 views
-1

我有兩個表tour_foreign &數據庫tour_foreign_residence,並希望合併這兩表在一起得到的PHP代碼的輸出如下例:將幾個數據庫表結合在一起?

我的表和值是:

enter image description here enter image description here

我想得到作爲輸出tour_foreign.id = tour_foreign_residence.relation

One-week tour of Istanbul_1 | 88888 & 99999 $ 112233 $ 445566 | Three nights and two days | 15:29
One-week tour of Istanbul_2 | 55555 & 66666 $ 77777 | Three nights and two days | 12:03
One-week tour of Istanbul_3 | 11111 & 22222 $ 33333 $ 44444 | Three nights and two days | 12:03

我的嘗試是這樣的,但它不給我什麼,我想在上面:

$this -> db -> query(" 
    SELECT 
      @rownum := @rownum + 1 rownum, 
      tour_foreign.id, 
      tour_foreign.name, 
      tour_foreign_residence.name_re, 
      tour_foreign.term, 
      tour_foreign.time_go, 
      tour_foreign.time_back, 
      tour_foreign.type_of_vehicle 
    FROM tour_foreign 
      INNER JOIN tour_foreign_residence 
      ON (tour_foreign.id = tour_foreign_residence.relation) 
      JOIN (SELECT @rownum := 0) r 
    WHERE tour_foreign.name LIKE "%' . $find . '%" 
      OR tour_foreign_residence.name_re LIKE "%' . $find . '%"  
") 

如何解決這個問題?

回答

0

嘗試使用GROUP_CONCAT()從你加入的名字tour_foreign_residence表

+0

請告訴我,它是如何在我的代碼? –

+0

我無法測試你的實際查詢,但你可以從添加到你的SELECT語句開始:GROUP_CONCAT(tour_foreign_residence.name_re ORDER BY tour_foreign_residence.name_re SEPERATOR「$」) –

+0

我在WHERE之後添加它,但是得到這個錯誤:'Error編號:1064 您的SQL語法有錯誤;請查看與您的MySQL服務器版本相對應的手冊,以便在第18行'GROUP_CONCAT(tour_foreign_residence.name_re ORDER BY tour_foreign_residence.nam')使用的正確語法使用' –

0

不知道爲什麼你在@rownum加入,它可能與你的結果集搞亂。嘗試把它拿出來,看看它是否有效。

你的內部連接看起來不錯,除了我從未見過它與包裹的parens,但我懷疑它會按預期工作。要測試你的查詢,你可以刪除複雜的where子句,只是把類似的東西在那裏tour_foreign.id = 1

喜歡的東西:

SELECT 
    tf.* 
FROM 
    tour_foreign AS tf 
INNER JOIN 
    tour_foreign_residence AS tfr 
ON 
    tfr.relation = tf.id 
WHERE 
    tf.id = 1 

我實現別名你再表名(TF,TFR和),因爲它們更容易處理。

+0

不起作用這一點,有錯誤:'錯誤編號:1051, 未知表 'tour_foreign', SELECT tour_foreign * FROM tour_foreign AS TF INNER JOIN tour_foreign_residence AS tfr ON tfr.relation = tf.id WHERE tf.id = 1' –

+0

@Nicole:抱歉,需要使用別名。我編輯了sql來反映這個變化。 –

+0

我用它爲:'$查詢= $這個 - >數據庫 - >查詢(」 \t \t SELECT TF * FROM tour_foreign AS TF INNER JOIN tour_foreign_residence AS TFR ON tfr.relation = TF。 ID WHERE tf.id = 1「);'這是沒有錯誤,但它沒有輸出? –

相關問題