我想从多个没有关系的独立表中提取数据。表是 tbl_temp1, tbl_temp2, tbl_temp3, tbl_temp4,so on 每个表都有公共字段,即 id,value,timestamp 但每个表中的记录都是独立的,因此它们之间没有关系。
我想水平生成所有表的值,即 Value_of_tbl_temp1 | 值_of_tbl_temp2 | 值_of_tbl_temp3 | 值_of_tbl_temp4 | ... | | | |
没有重复的数据
请帮我解决问题。
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
如果表有公共字段,那么您可以使用 UNION 查询从所有表中获取数据,然后根据需要显示它们。
这是 UNION 关键字的 mysql 文档页面:http: //dev.mysql.com/doc/refman/5.0/en/union.html
你可以试试这样的
(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)
..
休息你可以参考这里
或者您可以简单地选择
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
试试这个:
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