Mysql从两个具有相同结构的不同表中选择

时间:2013-03-29 15:04:46

标签: php mysql

你可以向我提供一些东西,如何推送两个不同的表但具有相同的结构,我的意思是所有信息都相同,只是表名不同,mailingsmailings_archive。 对于一张桌子,没关系

$query = sprintf("SELECT * FROM %smailings  WHERE hidden=0 AND draft=1 %sORDER BY category_id, mailing_segment", $this->dbprefix, $language);

$this->mailings[] = array('id' => $row->id,
                                      'mailing_naam' => $row->mailing_naam,
                                      'mailing_subject' => $row->mailing_subject,
                                      'mailing_from_name' => $row->mailing_from_name,
                                      'mailing_bounceaddress' => $row->mailing_bounceaddress,
                                      'mailing_body' => $row->mailing_body,
                                      'mailing_status' => $row->mailing_status,
                                      'mailing_segment' => $row->mailing_segment,
                                      'mailing_total_subscribers' => $row->mailing_total_subscribers,
                                      'mailing_total_sent' => $row->mailing_total_sent,
                                      'category_id' => $row->category_id,
                                      'utm_campaign' => $row->utm_campaign,
                                      'language' => $row->language);
        }                       

现在它看起来像这样,如何放入这个数组,另一个表数据?别忘了,每个字段都是一样的,只是表名不同。

2 个答案:

答案 0 :(得分:4)

(SELECT * FROM %smailings  WHERE hidden=0 AND draft=1 %sORDER BY category_id, mailing_segment)
UNION
(SELECT * FROM another_table WHERE hidden=0 AND draft=1 %sORDER BY category_id, mailing_segment)

(select * from table1)
union
(select * from table2)

但是这会导致一个无序的结果集,即使你在每个请求中加入“order by”,但这个可能是最快的。

如果您需要在表之间订购所有内容(1 .... 8),那么这是一种语法:

select * from table1
union
select * from table2 order by id

如果您想要两个单独的订单(例如一张表中的4 ... 8,另一张表中的1..4):

select * from 
(select * from test1 order by id asc) as t1
union all
(select * from test2 order by id asc);

答案 1 :(得分:1)

使用union方法..

尝试查询:选择1联合选择2