2012-04-05 50 views
0

好吧我有一個奇怪的場景,我不能改變數據庫結構,因爲我沒有這個權限。對於這個問題,我有三個表在這種情況下,如何從多個mysql表中選擇數據?

表1-

id(int) | name(varchar) | link_id(int) | link_to(tinyint) 
.............................................................. 
    1  | value1  | 1   | 2 
    2  | value2  | 3   | 2 
    3  | value3  | 1   | 3 
    4  | value4  | 2   | 3 
    5  | value5  | 3   | 3 

表2-

id(int) | data(varchar) 
............................ 
    1  | some1  
    2  | some2  
    3  | some3  

表3-

id(int) | data(varchar) 
............................ 
    1  | another1  
    2  | another2  
    3  | another3  

現在讓我來解釋一下:在table 1link_id是任table 2table 3,並link_toid場它是否與表2或3

現在我需要從所有3個表獲取的組合數據,例如對於table 1中的每個name字段,我從正確的表中獲得data字段,該字段由該行中的link_id和link_to字段定義。

是否有任何MySQL查詢實現這個?

回答

3

您可以嘗試使用UNION

(
SELECT t1.id,t2.data 
FROM table1 t1 
    INNER JOIN table2 t2 ON t1.link_id=t2.id AND t1.link_to=2 
) UNION (
SELECT t1.id,t3.data 
FROM table1 t1 
    INNER JOIN table3 t3 ON t1.link_id=t3.id AND t1.link_to=3 
) 
0

我接受的答案一致。 您也可以創建一個存儲過程並允許搜索。

# stored procedure 
DELIMITER $$; 
CREATE PROCEDURE `search_by_value`(
    in_searchValue VARCHAR(255) 
) 
BEGIN 
    DECLARE jointable INTEGER; 

    SELECT link_to INTO jointable FROM table1 WHERE name = in_searchValue; 
    IF (jointable = 2) THEN 
    SELECT * FROM table1 t1 left join table2 t2 on t1.link_id = t2.id WHERE t1.name = in_searchValue; 
    ELSEIF (jointable = 3) THEN 
    SELECT * FROM table1 t1 left join table3 t3 on t1.link_id = t3.id WHERE t1.name = in_searchValue; 
    END IF; 
END $$ 
DELIMITER; 

# call the sp 
call search_by_value('value1'); 
相關問題