简体   繁体   中英

SQL select two tables with no similar entry and different number of columns

Context: There's no mutual or similar entries in the two tables and there's different number of columns. The only point in common between those tables is: table 2 as table 1 as foreign key.

SELECT username, email 
FROM `table1`;

SELECT * 
FROM `table2` 
WHERE username = 'user1';

I would like a result that looks like this:

username: 'name', email:'anyemail@email.com'. (table 1)
column1: 'value', column2: number, column3: 'value', column4, column5 etc. (table 2).

Is there a way to collect those information in one single call for the database? I did try to play with UNION and one single SELECT but it does not work in that case.

Thank you.

UNION should work.

For the missing columns in table one you should enter NULL values with a Column name.

SELECT username, email, NULL as Column3 
FROM Table1
UNION ALL
SELECT column1, column2, column3 
FROM Table2

Or try also to convert the datatypes, so that they match.

SELECT CAST(username AS NVARCHAR(255) AS username, CAST(email AS NVARCHAR(255) AS email, CAST(NULL AS NVARCHAR(255) AS Column3
FROM Table1
UNION ALL
SELECT CAST(column1 AS NVARCHAR(255) AS username, CAST(column2 AS NVARCHAR(255) AS email, CAST(column3 AS NVARCHAR(255) AS Column3
FROM Table2

Try a temporary table: https://dev.mysql.com/doc/refman/5.7/en/create-table.html

Insert the results of the queries and make a SELECT request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM