2011-09-07 70 views
0

我已經得到了下面的表格中進行選擇:MySQL的三個表作爲一個

| table_one | table_two | table_three | table_four | 
| t_one_id | t_two_id | t_three_id | t_four_id | // primary key (auto increment) 
|   | two_nid | three_nid | four_nid | // foreign key to table_one.t_one_id 
| tone_date | ttwo_date | tthree_date | tfour_date | // time this was posted. 
// other fields 

而下面的查詢,

SELECT `table_two` . * , `table_three` . * , `table_four` . * 
FROM `table_two` 
JOIN (`table_three`) ON `table_three`.`three_nid`=1 
JOIN (`table_four` ) ON table_four`.`four_nid`=1 
WHERE `table_two`.`two_nid`=1 

,後面的數據:

table_one: 1, 11/08/2011 
table_two: 1, 1, 12/08/2011 
table_three: 1, 1, 13/08/2011 
table_four: 1, 1, 14/08/2011 

現在我的查詢不斷返回零結果,即使如此,但我期待它返回的是(當在每個表的日期排序):

result 1: 1 | 1 | 12/08/2011 | // this is from table_two 
result 2: 1 | 1 | 13/08/2011 | // from table three 
result 2: 1 | 1 | 14/08/2011 | // from four 

我也曾嘗試以下,但沒有成功:

SELECT * FROM table_two t2, table_three t3, table_four t4 WHERE t2.two_nid = 1 OR t3.three_nid=1 OR t4.four_nid=1; 

我要去哪裏錯了我的SQL查詢?

在此先感謝,如果需要更多信息,請不要猶豫。

回答

2

如果您想要將每個表格的結果顯示爲一個單獨的行,則需要有三個單獨的選擇,並將UNION結果。試試這個:

SELECT `table_two` . * 
FROM `table_one` 
JOIN (`table_two`) ON `table_two`.`two_nid`=`table_one`.`t_one_id` 
WHERE `table_one`.`t_one_id`=1 
UNION 
SELECT `table_three` . * 
FROM `table_one` 
JOIN (`table_three`) ON `table_three`.`three_nid`=`table_one`.`t_one_id` 
WHERE `table_one`.`t_one_id`=1 
UNION 
SELECT `table_four` . * 
FROM `table_one` 
JOIN (`table_four`) ON `table_four`.`four_nid`=`table_one`.`t_one_id` 
WHERE `table_one`.`t_one_id`=1 
+0

乾杯隊友,工作。 –

1
SELECT * FROM table1 
JOIN table2 ON table1.one_nid=table2.two_nid 
JOIN table3 ON table1.one_nid=table3.three_nid 
WHERE table1.one_nid=1 

...這當然如果它保證在table1每一行都有一個對應的行與其他各表的同一ID只會工作。否則,你應該閱讀約LEFT JOIN s。

1

您是否試圖「結合」結果? 如果是這樣,請檢查UNION關鍵字。