0

Is there a best way to make this SELECT statement with these two subqueries ?

SELECT N.ID, N.NAME 
   (SELECT TR.PUZZLE 
    FROM puzzles TR
    WHERE TR.TEAMID = "152" 
      AND TR.NID= N.ID) AS PUZZLE_OK,
   (SELECT TR.PUZZLE_BIS 
    FROM puzzles TR
    WHERE TR.TEAMID = "152" 
      AND TR.NID= N.ID) AS PUZZLE_BIS_OK
FROM news N
WHERE N.SERIESID = "1"

1 Answer 1

1

You can rewrite your query using a JOIN instead:

SELECT N.ID, N.NAME, TR.PUZZLE AS PUZZLE_OK, TR.PUZZLE_BIS AS PUZZLE_BIS_OK
FROM news N
JOIN puzzles TR ON TR.NID = N.ID
WHERE N.SERIESID = "1"
  AND TR.TEAMID = "152"

Note that if it's possible no entry in puzzles exists for a given ID value from news, you should use a LEFT JOIN and move the WHERE condition on puzzles into the JOIN. This will then return NULL values for PUZZLE_OK and PUZZLE_BIS_OK in the same way as your subqueries will:

SELECT N.ID, N.NAME, TR.PUZZLE AS PUZZLE_OK, TR.PUZZLE_BIS AS PUZZLE_BIS_OK
FROM news N
LEFT JOIN puzzles TR ON TR.NID = N.ID AND TR.TEAMID = "152"
WHERE N.SERIESID = "1"

Note I've changed the alias on news to N to keep the SELECT clause consistent with what was in the subqueries in your question.

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

3 Comments

Thanks. I don't know why I didn't think about JOIN.
I've tried with LEFT JOIN before to add my answer. I don't know we could add some extra after a LEFT JOIN ... ON ... with AND
@Padd When using a LEFT JOIN it's actually necessary to include conditions such as TR.TEAMID = "152" into the join condition, otherwise the LEFT JOIN becomes an INNER JOIN. See the manual

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.