简体   繁体   中英

Compare two tables with different column numbers in sql

I am using Sybase for my SQL coding.

I was comparing tables which have the same columns such as follows:

SELECT name, date, time, location
FROM
(SELECT * FROM table1
UNION ALL  
SELECT * FROM table2) data
GROUP BY name, date, time, location
HAVING count(*)!=2

Now, I want to be able to compare the table1 and table2 but now table2 has another column called origin and I am not sure on how to extend my current logic to make it happen.

---Intention: to be able to compare the two tables with varying column numbers
---How to modify this code to do it?

I want to be able to show the differences between the two tables after the query.

May someone guide me? I dont want to use joins or minus, I prefer to use the UNION way.

If you want to union two different tables, you must make up missing columns. Eg:

SELECT name, date, time, location, origin FROM table2
UNION ALL
SELECT name, date, time, location, null as origin FROM table1

I think the problem is that you actually want to ignore the extra column. The problem with using select * is that things can change.

SELECT name, date, time, location
FROM (
    SELECT name, date, time, location FROM table1
    UNION ALL  
    SELECT name, date, time, location FROM table2
) data
GROUP BY name, date, time, location
HAVING count(*) != 2

If you're not going to use select * in one half of the union there isn't any reason include origin in the first place.

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