Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在mysql中选择多个表的公共值_Mysql_Database_Join - Fatal编程技术网

在mysql中选择多个表的公共值

在mysql中选择多个表的公共值,mysql,database,join,Mysql,Database,Join,我正在编写一个php代码来计算一个值。我有4个表,每个表有2列。它们的标题是相同的。我想获取表的第二列,这些表的第一列上有值,比如“MAN”: 以下是我的表及其虚拟值: 我用where子句连接了'dst'上的表,但是当一个表没有公共值并且在mysql中没有完全外部连接时,问题就会出现。我知道我们可以用union all操作来模拟这一点,但我需要一种有效的方法来实现这一点。 以下是我的尝试: select t1.dst, t1.pay as pay, t2.pay as pay2, t3.pay

我正在编写一个php代码来计算一个值。我有4个表,每个表有2列。它们的标题是相同的。我想获取表的第二列,这些表的第一列上有值,比如“MAN”: 以下是我的表及其虚拟值:

我用where子句连接了'dst'上的表,但是当一个表没有公共值并且在mysql中没有完全外部连接时,问题就会出现。我知道我们可以用union all操作来模拟这一点,但我需要一种有效的方法来实现这一点。 以下是我的尝试:

select t1.dst, t1.pay as pay, t2.pay as pay2, t3.pay as pay3, t4.pay as pay4 from t1 left outer join t2 on t1.dst = t2.dst left outer join t3 on t3.dst=t2.dst left outer join t4 on t1.dst=t4.dst where t1.dst='man';
它是虚拟的,因为除了特殊情况外,左外连接对于这个目的不是真的

实际上我想要这个:

先联后转

drop table if exists t,t1,t2,t3;
create table t  (dst varchar(3),value int);
create table t1 (dst varchar(3),value int);
create table t2 (dst varchar(3),value int);
create table t3 (dst varchar(3),value int);


insert into t values ('abc',10),('man',10);
insert into t1 values ('abc',10),('man',5);
insert into t2 values ('abc',10),('man',10);
insert into t3 values ('abc',10);

select  dst,
          MAX(CASE WHEN tbl = 't' then value end) as t1,
          MAX(CASE WHEN tbl = 't1' then value end) as t1,
          MAX(CASE WHEN tbl = 't2' then value end) as t2,
          MAX(CASE WHEN tbl = 't3' then value end) as t3  
from
(
select 't' as tbl,dst,value from t where dst = 'man'
union
select 't1' as tbl,dst,value from t1 where dst = 'man'
union
select 't2' as tbl,dst,value from t2 where dst = 'man'
union
select 't3' as tbl,dst,value from t3 where dst = 'man'
) s 
group by s.dst;

+------+------+------+------+------+
| dst  | t1   | t1   | t2   | t3   |
+------+------+------+------+------+
| man  |   10 |    5 |   10 | NULL |
+------+------+------+------+------+
1 row in set (0.00 sec)

联合所有人而不是加入?您希望您的输出如何显示?@P.Salmon我想要一个包含cols的表格。每个cols的标题是表名,其值是支付值,例如“man”。如果该表中不存在man,您希望所有表名都为零值,还是只希望存在man的表名?@P.Salmon“仅存在man的表名”非常棒!表名与“man”对应的支付值!看见我想使用pay为每个具有特定dst的表计算一个值,如“man”,并返回最便宜的值。我很困惑-您上一次的评论与您在上次编辑中添加的图像相矛盾,如果您只想在所有表中找到最便宜的值,为什么要这么做-