[英]MySQL full join (union) with ambiguous column names
我对 MySQL 在这么多年之后仍然不支持 FULL JOIN 感到非常失望(为什么?)而且我必须使用 UNION 作为解决方法。 说我在使用以下查询时遇到问题。 我有两个表作为例子:
电脑
id userid owner cpu
1 1 Jack 3.4
2 1 Jack 3.4
3 2 Sara 3.0
监视器
id userid owner inch
1 1 Jack 22
2 1 Jack 22
3 3 Mark 17
4 4 Luke 32
基本上我有一个计算机列表,其中包含已分配给所有者的规格。 同样,我有一个带有规格的显示器列表,每个显示器都分配给了一个所有者。 我想按所有者将这两个表合并到这个结果中:
id userid owner cpu id userid owner inch
1 1 Jack 3.4 1 1 Jack 22
2 1 Jack 3.4 2 1 Jack 22
3 2 Sara 3.0 null null null null
null null null null 3 3 Mark 17
null null null null 4 4 Luke 32
我可以通过这个查询成功得到上面的结果:
SELECT * FROM computers AS a
LEFT OUTER JOIN monitors AS o on a.owner = o.owner
UNION
SELECT * FROM computers AS a
RIGHT OUTER JOIN monitors AS o on a.owner = o.owner
问题是:
现在总结一下我在伪查询中所说的内容,我会:
SELECT id AS a_id, userid AS a_userid, owner AS a_owner but NOT cpu FROM computer WHERE cpu = 3.4
所有者联合和加入:
SELECT id AS b_id, userid AS b_userid, owner AS b_owner, inch AS b_inch FROM monitor WHERE inch = 22
感谢您的时间。
模拟full outer join
联接的另一种方法是使用子查询获取完整的值列表(在您的情况下为owner
)。 然后使用left outer join
引入其他值。 根据你的描述:
select c.id as c_id, c.userid as c_userid, o.owner as owner,
m.id as m_id, m.user_id as m_userid, m.inch
from (select owner from computers union
select owner from monitors
) o left outer join
computers c
on o.owner = c.owner left outer join
monitors m
on o.owner = m.owner;
但是,您提到的查询不会生成这些结果。 它将为“Jack”生成四个结果。
编辑:
我怀疑您想匹配owner
、 id
和user_id
:
select c.id as c_id, c.userid as c_userid, o.owner as owner,
m.id as m_id, m.user_id as m_userid, m.inch
from (select owner, id, userid from computers union
select owner, id, userid from monitors
) o left outer join
computers c
on o.owner = c.owner and o.userid = c.userid and o.id = c.id left outer join
monitors m
on o.owner = m.owner and o.userid = m.userid and o.id = m.id;
这是 cpu = 3.4 和 Inch = 22 上的完整外部联接。首先获取所有计算机并加入显示器,然后获取所有显示器并加入计算机。 主表条件在 WHERE 子句中,外连接条件在 ON 子句中。
SELECT a.userid, a.owner, a.id as computer_id, o.id as monitor_id, o.inch
FROM computers AS a
LEFT OUTER JOIN monitors AS o
ON a.owner = o.owner and a.userid = o.userid and o.inch = 22
WHERE a.cpu = 3.4
UNION
SELECT o.userid, o.owner, a.id as computer_id, o.id as monitor_id, o.inch
FROM monitors AS o
LEFT OUTER JOIN computers AS a
ON a.owner = o.owner and a.userid = o.userid and a.cpu = 3.4
WHERE o.inch = 22;
但是,这可以通过仅添加第一个选择未找到的记录(即没有匹配计算机的显示器)来加快速度。 然后您可以使用 UNION ALL 而不是 UNION,这可以为 dbms 节省大量工作。 您只需拿起外部连接表的不可为空的线圈。 当它为 NULL 时,记录是外连接的。
SELECT a.userid, a.owner, a.id as computer_id, o.id as monitor_id, o.inch
FROM computers AS a
LEFT OUTER JOIN monitors AS o
ON a.owner = o.owner and a.userid = o.userid and o.inch = 22
WHERE a.cpu = 3.4
UNION ALL
SELECT o.userid, o.owner, a.id as computer_id, o.id as monitor_id, o.inch
FROM monitors AS o
LEFT OUTER JOIN computers AS a
ON a.owner = o.owner and a.userid = o.userid and a.cpu = 3.4
WHERE o.inch = 22 and o.owner is null;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.