Welcome Guest, Not a member yet? Register   Sign In
SQL query with unique keys between two tables
#1

[eluser]jleequeen[/eluser]
I'm trying to figure out how to get a total between two tables but only counting a row once if it is in both tables. Assuming I have the following:

table1

id
0000
0001
0002
0010

table 2

id
0000
0004
0010
0011

I would want to do a count between the tables and only return the unique total between the two. So in the example above the answer should be: 6 (0000 and 0010 would only count once in the total since they are duplicated).

I'm using active record but not sure if I need to write a custom query to do this. Any insight?
#2

[eluser]davidbehler[/eluser]
You could use a union to do so.

In your example it would be something like:

Code:
(select id from table1)
union distinct
(select id from table2);

And then just count the number of rows you get returned.




Theme © iAndrew 2016 - Forum software by © MyBB