从具有不同列数的两个表中选择* [英] select * from two tables with different # of columns

查看:118
本文介绍了从具有不同列数的两个表中选择*的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从两个不同的表中选择不同的列,例如:

How would I select different columns from two different tables, such as:

SELECT username, email FROM `table1` 
UNION
 SELECT * FROM `table2` WHERE username = 'user1';

我收到错误"#1222 - The used SELECT statements have a different number of columns".据我了解,UNION无法正常工作,

I'm getting an error "#1222 - The used SELECT statements have a different number of columns". From what I understand UNION will not work,

有没有一种方法可以完成此操作,因为我需要不等数量的列和行,并且两个表中没有相互/相似的条目(即,user1未在表1中列出)?

Is there a way to accomplish this, since I would need unequal number of columns and rows and there are no mutual/similar entries in the two tables (i.e. user1 is not listed in table1)?

这不能在一个查询中完成吗?

Can this not be done in one query?

谢谢!

推荐答案

您可以使用别名fake缺少的列-例如

You can fake the missing columns using an alias - e.g.

 SELECT username, email, '' as name FROM `table1` 
 UNION
 SELECT username, email, name FROM `table2` 
 WHERE username = 'user1';

名称在表2中,但不在表1中

where name is in table2, but not in table1

除非您将UNIONS与JOINS混淆:

Unless you're confusing UNIONS with JOINS:

SELECT table1.*, table2.* FROM
table1 INNER JOIN table2
ON table1.username = table2.username

这将合并两个表,因此您将所有列都放在同一行.

this would merge both tables, so you get all the columns on the same row.

这篇关于从具有不同列数的两个表中选择*的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆