1

My MariaDB doesn't support IN and I cannot seem to write a proper query that uses JOIN and gives the same result. Here's the query with IN

SELECT * FROM topics WHERE topic_id IN 
( SELECT DISTINCT(topic) FROM answers 
ORDER BY date LIMIT 500 )

How would that query translate to something that doesn't use IN but JOIN (prefrably)?

2
  • If a topic occurs in two answers with different dates, which date should apply to the LIMIT??
    – Rick James
    Commented Apr 20, 2017 at 22:23
  • Oh, which table is each column in?? Please qualify column names with the table name (or alias).
    – Rick James
    Commented Apr 20, 2017 at 22:24

3 Answers 3

1

You can use a correlated sub-query.

SELECT * 
FROM topics 
INNER JOIN
(SELECT DISTINCT(topic) as topic FROM answers LIMIT 500) x on x.topic = topic_id  
2
  • The only issue I have with correlated sub-query is that it can perform worse than a set based query. Usually it can be done with creative joins, but sometimes it makes it easier to use correlated sub-queries. Plus sometimes based on the RDMS and optimizer, it will run the SQL like a join anyway. Commented Apr 20, 2017 at 16:41
  • 1
    Can't argue that @Shaulinator and more often than not the optimizer will treat it like a join.
    – S3S
    Commented Apr 20, 2017 at 16:45
0

try this one with subquery. As you wrote your code I suppose you prefer an INNER JOIN.

I just got rid of ORDER BY, because it only makes sense on the outermost query. And mostly because if you select distinct you can't order by without duplicate values... try to explain me better your ordering, because we may need another nested select.

Answer this: "2 equal topic FROM answers with different date, is it possible? If so which date to consider?"

SELECT A.* 
FROM topics A INNER JOIN
( 
SELECT DISTINCT(topic) AS topic_B FROM answers 
LIMIT 500 
) B
ON (A.topics_id = B.topic_b)
0

Aliasing your table helps for keeping joins straight in your head. (The t and a as seen below) Inner join only returns where results match, similar function to where in.

SELECT T.* FROM topics t
INNER JOIN
(
 SELECT DISTINCT(topic) 
 FROM answers
 ORDER BY date LIMIT 500
) a
ON t.topic_id = a.topic

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.