Skip to content
Advertisement

SQL – specific requirement to compare tables

I’m trying to merge 2 queries into 1 (cuts the number of daily queries in half): I have 2 tables, I want to do a query against 1 table, then the same query against the other table that has the same list just less entries.

Basically its a list of (let’s call it for obfuscation) people and hobby. One table is ALL people & hobby, the other shorter list is people & hobby that I’ve met. Table 2 would all be found in table 1. Table 1 includes entries (people I have yet to meet) not found in table 2

The tables are synced up from elsewhere, what I’m looking to do is print a list of ALL people in the first column then print the hobby ONLY of people that are on both lists. That way I can see the lists merged, and track the rate at which the gap between both lists is closing. I have tried a number of SQL combinations but they either filter out the first table and match only items that are true for both (i.e. just giving me table 2) or just adding table 2 to table 1.

Example of what I’m trying to do below:

+---------+----------+--+----------+---------+--+---------+----------+
| table1  |          |  |  table2  |         |  |  query  |          |
+---------+----------+--+----------+---------+--+---------+----------+
| name    | hobby    |  | activity | person  |  | name    | hobby    |
| bob     | fishing  |  | fishing  | bob     |  | bob     | fishing  |
| bill    | vidgames |  | hiking   | sarah   |  | bill    |          |
| sarah   | hiking   |  | planking | sabrina |  | sarah   | hiking   |
| mike    | cooking  |  |          |         |  | mike    |          |
| sabrina | planking |  |          |         |  | sabrina | planking |
+---------+----------+--+----------+---------+--+---------+----------+

Normally I’d just take the few days to learn SQL a bit better however I’m stretched pretty thin at work as it is!

I should mention the table 2 is flipped and the headings are all unique (don’t think this matters)!

Advertisement

Answer

I think you just want a left join:

select t1.name, t2.activity as hobby
from table1 t1 left join
     table2 t2
     on t1.name = t2.person;
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement