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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With