Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select * from two tables with different # of columns

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

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

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

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?

thank you!

like image 430
d-_-b Avatar asked May 18 '12 23:05

d-_-b


1 Answers

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';

where name is in table2, but not in table1

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.

like image 127
web_bod Avatar answered Oct 04 '22 23:10

web_bod