繁体   English   中英

将多个表中的行作为单个结果?

[英]Grabbing rows from multiple tables as single result?

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

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

谢谢...

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的字段大小。

我假设MySql这样做:

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

在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 |
+------+---------+

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM