1

我正在编写一个脚本,该脚本从不同的 mysql 表中获取一些数据:

#!/bin/bash
/usr/bin/mysql --password=****** --database=mydb<<EOMYSQL
select field1, field2 from table1 left join table2 on etc
into outfile '/home/jm/mysql/file1.txt';
select field3 from table3 left join table4 on etc
into outfile '/home/jm/mysql/file2.txt';
select field4,field5,field6,field7 from table5 left join table6 on etc
into outfile '/home/jm/mysql/file3.txt';
EOMYSQL

我的“问题”是我需要使用 3 个不同的输出文件,然后将它们合并。有什么方法可以将 3 个查询的输出放在一起?,例如:

field1 field2 field3 field4 field5 field6 field7 

谢谢,

PS:尝试“联合所有”,但看起来每个查询需要相同数量的字段。

4

4 回答 4

3

是的,UNION每个查询都需要相同数量的字段,但您可以使用空字符串填充它们:

select field1, field2, "", "", "", "", "" from table1 left join table2 on etc
union
select "", "", field3, "", "", "", "" from table3 left join table4 on etc
union
select "", "", "", field4, field5, field6, field7 from table5 left join table6 on etc

您还可以使用NULL

select field1, field2, NULL, NULL, NULL, NULL, NULL from table1 left join table2 on etc
union
select NULL, NULL, field3, NULL, NULL, NULL, NULL from table3 left join table4 on etc
union
select NULL, NULL, NULL, field4, field5, field6, field7 from table5 left join table6 on etc
于 2013-01-02T13:23:57.783 回答
1

如果您想按列加入这些文件,您应该使用该paste实用程序:

cd /home/jm/mysql/
paste file1.txt file2.txt file3.txt
于 2013-01-02T13:15:38.157 回答
1

看起来你需要这个paste命令。

% cat A.csv 
dog,cat
bird,tiger

% cat B.csv 
bear,lion
weasel,trout

% paste -d, A.csv B.csv 
dog,cat,bear,lion
bird,tiger,weasel,trout

-d标志更改分隔符(默认为 TAB)。

于 2013-01-02T13:18:21.037 回答
1

在没有看到任何示例数据甚至您的表结构的情况下,如果您想在 SQL 中执行此操作,那么您可以使用以下内容。

如果您有一个可以在每个查询结果之间连接的字段,那么您可以使用 aLEFT JOIN返回数据:

select *
from
(
  select t1.field1, t1.field2
  from table1 t1
  left join table2 t2
    on t1.field1 = t2.field1
) t1t2
left join
(
  select t3.field3
  from table3 t3
  left join table4 t4
    on t3.field3 = t4.field3
) t3t4
  on t1t2.field1 = t3t4.field3
left join
(
  select t5.field4, t5.field5, t5.field6, t5.field7
  from table5 t5
  left join table6 t6
    on t5.field4 = t6.field4
) t5t6
  on t1t2.field1 = t5t6.field4;

请参阅带有演示的 SQL Fiddle

如果您没有可以加入的字段,那么您可以使用CROSS JOIN

select *
from
(
  select t1.field1, t1.field2
  from table1 t1
  left join table2 t2
    on t1.field1 = t2.field1
) t1t2
cross join
(
  select t3.field3
  from table3 t3
  left join table4 t4
    on t3.field3 = t4.field3
) t3t4
cross join
(
  select t5.field4, t5.field5, t5.field6, t5.field7
  from table5 t5
  left join table6 t6
    on t5.field4 = t6.field4
) t5t6;

请参阅带有演示的 SQL Fiddle

于 2013-01-02T13:23:10.653 回答