1

I'm doing an sql query on two tables in a database. I want to select data from table one only if the data in columns one and columns two on both tables match. Please help.. Tables one and two have the same structure.

  • 3
    A `JOIN` is perhaps what you are looking for. Sample table data, and the expected result may however make me change my mind. – jarlh Apr 13 '16 at 12:15
  • Hello @jarlh please how do set up such query.. I'm an sql newbie.. How do I select all from table one only if columns A and Columns B on both tables have the same data.. – CodeAndTheory Apr 13 '16 at 12:19

2 Answers2

1

That sounds like a job for EXISTS() which will check if a record with the same (column1,column2) exists.

SELECT * FROM Table1 t
WHERE EXISTS(SELECT 1 FROM Table2 s
             WHERE t.column1 = s.column1 and t.column2 = s.column2)

Can also be done with an INNER JOIN :

SELECT t.* FROM Table1 t
INNER JOIN Table2 s
 ON(t.column1 = s.column1 and t.column2 = s.column2)
sagi
  • 40,026
  • 6
  • 59
  • 84
  • Hello sabi, thanks for the answer. From your sql above, what does the variable "t" mean..? I'm lost there. – CodeAndTheory Apr 13 '16 at 12:23
  • @CodeAndTheory An alias, not variable, instead of writing table1.ColName every time I call table1 `t` and then I can use t. – sagi Apr 13 '16 at 12:25
  • Thanks for clarification. I can't upvote for now since my reputation is low. But it's looking like exactly what I need. Will sure visit this in future. Thanks again. – CodeAndTheory Apr 13 '16 at 12:29
0

I would use INNER JOIN:

SELECT column_name(s)
FROM table1
INNER JOIN table2
ON table1.column_name=table2.column_name

Hope this helps you :)

Akimbo
  • 13
  • 3