2012-04-05 55 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'); 
相关问题