从多个表中抓取行作为单个结果?

Ei *_*ung 1 php mysql

我有2张桌子.表1具有字段A,B,C,D,表2具有字段A,B.两个表的字段A和B具有相同的记录类型.我想从字段A和B的两个表中获取单个结果的记录.

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

谢谢...

pax*_*blo 8

SQL中有一个union子句可以满足您的需求:

select a,b from table1
    where <where-clause>
union all select a,b from table2
    where <where-clause>
Run Code Online (Sandbox Code Playgroud)

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

select a,b,c,d from table1
    where <where-clause>
union all select a,b,' ' as c,' ' as d from table2
    where <where-clause>
Run Code Online (Sandbox Code Playgroud)

可能需要扩展第二个查询中的空格以适合c和d的字段大小.


Wil*_*ung 7

我假设MySql这样做:

从table1中选择a,b,其中your_criteria = test_value union从table2中选择a,b,其中your_criteria = test_value


小智 5

在MySQL Server版本中确认了Union解决方案: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 |
+------+---------+
Run Code Online (Sandbox Code Playgroud)