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.

2
  • 3
    A JOIN is perhaps what you are looking for. Sample table data, and the expected result may however make me change my mind. Commented Apr 13, 2016 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.. Commented Apr 13, 2016 at 12:19

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

3 Comments

Hello sabi, thanks for the answer. From your sql above, what does the variable "t" mean..? I'm lost there.
@CodeAndTheory An alias, not variable, instead of writing table1.ColName every time I call table1 t and then I can use t.
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.
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 :)

1 Comment

Amazing. This one also worked. Thank you Akimbo.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.