2008-10-07 37 views
1

我有2张桌子。表1具有字段A,B,C,D,并且表2具有字段A,B。两个表的字段A和B具有相同的记录类型。我希望从字段A和B的两个表中获取记录作为单个结果。从多个表中抓取行作为单一结果?

PHP + MySql中是否有任何查询或函数?

谢谢...

回答

7

我认为MySQL的这个:

从表1从表2中选择一个,b,其中your_criteria = test_value 工会 选择A,B,其中your_criteria = test_value

8

有SQL中的union子句可以做你想做的事情:

select a,b from table1 
    where <where-clause> 
union all select a,b from table2 
    where <where-clause> 

或者,如果你想要所有的字段(空格为表2):

select a,b,c,d from table1 
    where <where-clause> 
union all select a,b,' ' as c,' ' as d from table2 
    where <where-clause> 

在第二查询中的空间可能需要被扩展以适合c和d中的字段大小。

+0

感谢您有用的答案。如果可以,我想接受所有三个答案...... :) – 2008-10-07 00:54:33

5

联盟解决方案在MySQL服务器版本证实:5.0.51a-3ubuntu5.1(Ubuntu的)

create database foo; 
create table bill(a int, b varchar(10)); 
create table ted(a int, b varchar(10), c datetime, d boolean); 
insert into bill values (10, 'foo'), (20, 'bar'); 
insert into ted values (5, 'splot', now(), true), (10, 'splodge', now(), false); 
select a,b from bill where a<=10 union select a,b from ted where a<=10; 
+------+---------+ 
| a | b  | 
+------+---------+ 
| 10 | foo  | 
| 5 | splot | 
| 10 | splodge | 
+------+---------+ 
+0

谢谢。你的回答对我真的很有帮助... – 2008-10-07 00:56:12

相关问题