1

I want to write SQL query which select some columns from the first table and all columns from the second table.

ID is the PK in table1 and id is the FK in table2.

Is this correct:

SELECT ID, table2.ALL
FROM table1
INNER JOIN table2 ON table1.ID = table2.id 
WHERE table1.ID= x AND table1.Column3 = 'y'
2
  • 1
    Have you tried running the query and seeing what happens? Commented Feb 10, 2012 at 16:43
  • Exception happen: " Incorrect syntax near '.' Commented Feb 10, 2012 at 16:47

4 Answers 4

4

Do you have a column called ALL in table2 or do you want to select all columns from table2 ??

If you want all columns use table2.* instead:

SELECT table1.ID, table2.*
FROM table1 
INNER JOIN table2 ON table1.ID = table2.id 
WHERE table1.ID= x AND table1.Column3 = 'y'

Also, since you have ID in both tables, you need to specify which one to select in your statement.

Update: if you don't want all columns from table2, then you need to explicitly specify the columns that you do want:

SELECT 
    t1.ID, 
    t2.column1, t2.column2, ....., t2.columnN
FROM table1 t1 
INNER JOIN table2 t2 ON t1.ID = t2.id 
WHERE t1.ID= x AND t1.Column3 = 'y'
Sign up to request clarification or add additional context in comments.

4 Comments

Mr.marc_s I don't want to choose the FK column in the table2, how can do it?
@H_wardak: if you want don't want to select everything from a table, you need to explicitly specify which columns you want
I need all columns except the FK. Is there another way?
@H_wardak: yes, that's fine - then you need to explitly specify all the columns - except the FK ...... there is no magic way to specify "everything but this one column" ....
3

You can't use table2.ALL. That will look for a column called "All" in table2. You want to use table2.* instead.

SELECT table1.ID, table2.*
FROM   table1 INNER JOIN table2 on table1.ID = table2.id
WHERE  table1.ID = x AND table1.Column3 = 'y'

Comments

1

Instead of "ALL", use *:

SELECT t1.ID, t2.* FROM table1 as t1
INNER JOIN table2 as t2 
ON t1.ID = t2.id 
WHERE t1.ID = x 
AND t1.Column3 = 'y'

Comments

0

Do it like this:

select t1.ID, t2.*
from table1 t1
inner join table2 t2 on table1.ID = table2.id
WHERE t1.ID=xxx AND t1.Column3 = 'y'

Replace xxx by the ID that you want.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.