如何从没有关系的多个独立表中获取数据

时间:2012-06-06 05:22:34

标签: mysql sql

我想从没有关系的多个独立表中提取数据。 表是tbl_temp1,tbl_temp2,tbl_temp3,tbl_temp4,依此类推 每个表都有公共字段,即id,value,timestamp 但是记录在每个表中都是独立的,因此它们之间没有任何关系。

我想水平生成所有表的值 即 - Value_of_tbl_temp1 | Value_of_tbl_temp2 | Value_of_tbl_temp3 | Value_of_tbl_temp4 | ...              | | | |

没有重复的数据

请帮我解决问题。

4 个答案:

答案 0 :(得分:2)

SELECT un.common_id, COALESCE(t1_value), COALESCE(t2_value), COALESCE(t3_value) FROM
(SELECT t1.common_id, t1.value as t1_value, NULL AS t2_value, NULL AS t3_value FROM t1
UNION 
SELECT t2.common_id, NULL, t2.value, NULL FROM t2
UNION 
SELECT t3.common_id, NULL, NULL, t3.value FROM t3) AS un
GROUP BY un.common_id

答案 1 :(得分:0)

如果表有公共字段,那么您可以使用UNION查询从所有表中获取数据,然后按您的需要显示它们。

以下是UNION关键字的mysql文档页面: http://dev.mysql.com/doc/refman/5.0/en/union.html

答案 2 :(得分:0)

您可以尝试这样的事情

(SELECT value_of_tbl_temp1 FROM tbl_temp1 ORDER BY value_of_tbl_temp1 LIMIT 10)
UNION
(SELECT value_of_tbl_temp2 FROM tbl_temp2 ORDER BY value_of_tbl_temp2 LIMIT 10)
..

休息,您可以参考here

或 您只需选择

即可
select tbl1.value_of_tbl_temp1 as value_of_tbl_temp1,
tbl2.value_of_tbl_temp2 as value_of_tbl_temp2,
tbl3.value_of_tbl_temp3 as value_of_tbl_temp3,
tbl4.value_of_tbl_temp2 as value_of_tbl_temp4,
from 
tbl_temp1 as tbl1,
tbl_temp2 as tbl2,
tbl_temp3 as tbl3,
tbl_temp4 as tbl4

答案 3 :(得分:0)

试试这个:

SELECT 
    tbl1.value as Value_of_tbl_temp1,
    tbl2.value as Value_of_tbl_temp2,
    tbl3.value as Value_of_tbl_temp3,
    tbl4.value as Value_of_tbl_temp4
FROM
    tbl_temp1 tbl1, 
    tbl_temp2 tbl2, 
    tbl_temp3 tbl3, 
    tbl_temp4 tbl4

试试这个。

SELECT
    tbl1.value AS Value_of_tbl_temp1,
    tbl2.value AS Value_of_tbl_temp2,
    tbl3.value AS Value_of_tbl_temp3,
    tbl4.value AS Value_of_tbl_temp4
FROM
(SELECT 
    VALUE,
    @rownum1:=@rownum1+1 rank
FROM
    tbl_temp1 tbl1, 
 (SELECT @rownum1:=0) r 
ORDER BY tbl1.id ASC) tbl1
INNER JOIN
(SELECT 
    VALUE,
    @rownum2:=@rownum2+1 rank
FROM
    tbl_temp2 tbl2, 
     (SELECT @rownum2:=0) r 
ORDER BY tbl2.id ASC) tbl2
ON
tbl1.rank = tbl2.rank
INNER JOIN
(SELECT 
    VALUE,
    @rownum3:=@rownum3+1 rank
FROM
    tbl_temp3 tbl3, 
    (SELECT @rownum3:=0) r 
ORDER BY tbl3.id ASC) tbl3
ON
tbl1.rank = tbl3.rank
INNER JOIN
(SELECT 
    VALUE,
    @rownum4:=@rownum4+1 rank
FROM
    tbl_temp4 tbl4, 
     (SELECT @rownum4:=0) r 
ORDER BY tbl2.id ASC) tbl4
ON
tbl1.rank = tbl4.rank