I'm trying to construct a query that compares two tables with identical structure
Table 1:
ID | Data
Table 2:
ID | Data
ID is a nonunique key (Data is repeatable but ID|Data combos are unique). I need a list of IDs where the COUNT of those IDs is greater in Table 2 than in Table 1.
So for example, if
Table 1
a | data
a | data1
b | data2
Table 2
a | data
a | data1
b | data2
b | data3
would generate the output "b"
This feels like it should be easy, but my head is scrambled right now. I'm doing this in mysql if that affects options.
Compare Two Tables using UNION ALL Select * from ( Select Id_pk, col1, col2...,coln from table1, 'Old_table' Union all Select Id_pk, col1, col2...,coln from table2, 'New_tbale' ) cmpr order by Id_pk; The above query returns the all rows from both tables as old and new.
Use the Find Unmatched Query Wizard to compare two tables One the Create tab, in the Queries group, click Query Wizard. In the New Query dialog box, double-click Find Unmatched Query Wizard. On the first page of the wizard, select the table that has unmatched records, and then click Next.
Compare two tables by using joins. To compare two tables by using joins, you create a select query that includes both tables. If there is not already an existing relationship between the tables on the fields that contain the corresponding data, you create a join on the fields that you want to examine for matches.
By using UNION, UNION ALL, EXCEPT, and INTERSECT, we can compare two queries and get the necessary output as per our requirement. Given examples are simple to follow, we can have complex queries and can apply the mentioned constructs in them and can compare.
To get the count for each key,
select count(*) as count, ID from Table1 group by ID
So, use this as a sub-query in the from clause, and join the tables.
select tt1.ID
from (select count(*) as count, ID from Table1 group by ID) tt1
inner join (select count(*) as count, ID from Table2 group by ID) tt2
on tt1.ID = tt2.ID
where tt1.count < tt2.count
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