0

Basically I have two tables. 1 and 2. I need the field2 column in the table2 table to return multiple rows. I tried the below join (simplified the columns) but unfortunately it returns me only one result.

SELECT table1.field1, table1.field2, table1.field3, sub_q.field4
FROM table1
JOIN (
    SELECT t2.field4, t2.filter1, t2.filter2 FROM table2 t2
) sub_q ON (sub_q.filter1 = table1.id AND sub_q.filter2 = 1) 
##Should return multiple rows
##but returns only one!
WHERE table1.id = ..;

Edit:

I created a schema here: http://sqlfiddle.com/#!9/1c5737 with the select query as

SELECT t1.field1, t1.field2, t1.field3, t2.field1
FROM table1 t1
JOIN table2 t2 ON t2.filter1 = t1.id AND t2.filter2 = 1
WHERE t1.id = 1;

Only to find out that it works there, so I come back in shame to accept the answer and check where I messed up in my query (probably one of the fields)

1 Answer 1

2

Why are you using a subquery in the join? This is how it should be written:

SELECT table1.field1, table1.field2, table1.field3, t2.field1
FROM table1 t1
JOIN table2 t2 ON t2.filter1 = table1.id AND t2.filter2 = 1 

Also it is likely that you need LEFT JOIN (or INNER JOIN) instead of JOIN, but cannot be sure without more details on what you're trying to achieve.

Sign up to request clarification or add additional context in comments.

2 Comments

I dont know if I am missing something but it still returns me the first row (from the join obv) only. I need the rows from the join to be added on the other selected rows only if they have the same filter1 (id) so I guess its a left join
We really need more details. Edit the question and add sample data and expected results.

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.