tags:

views:

61

answers:

4

I have 2 tables:

  • TOPICS (id, title)
  • ANSWERS (id, id_topic, id_user, answer)

...and i want to do a select to detect all the questions belonging to a user in one select.

I tried to do a join, but that doesn't work since if a user answered a topic twice, it will return 2 rows with the same topic. I tried to do a SELECT DISTINCT, but that fails also.

A: 

I can't quite understand your question, could you please make it a little more clearer?

lemon
This is more a comment. But since you don't have enough rep, you'll need to find questions that aren't so vague/poorly written to help rep up.
random
yeah not enough rep, so i posted this as an answer :(
lemon
A: 
SELECT * FROM topics
WHERE id IN (SELECT id_topic FROM answers WHERE id_user = ?);

It doesn't matter if some values are returned more than once by the subquery. Any given row in the outer query will either match or not.

Like E. F. Codd said, "if something is true, saying it twice doesn't make it more true."

Bill Karwin
A: 

If you are trying to see which topics a user answered, try this:

SELECT t.title, a.id_user, COUNT(a.id)
FROM topics t LEFT JOIN answers a
  ON (t.id=a.topic_id)
GROUP BY t.title, a.id_user;

The above will give you the title, user and number of answers from that user (if any). If you only want answered topics, use JOIN instead of LEFT JOIN.

dnagirl
+1  A: 

Try:

SELECT id, topic 
  FROM topics 
 WHERE id IN (SELECT id_topic 
                FROM answers 
                WHERE id_user = <USERID>)

...or:

SELECT id, topic 
  FROM topics 
 WHERE EXISTS (SELECT * 
                 FROM answers 
                WHERE id_user = topics.id)

...and test for performance according to your indexing regimen. Recent versions of MySQL only.

Larry Lustig
I wish people would stop harping on MySQL for its former lack of support for subqueries. MySQL has now supported subqueries for nearly *five years* (since 2004-10-23). Version 4.1, which introduced support for subqueries, is so old now that it will reach its end of life this year (2009-12-31). See http://www.mysql.com/about/legal/lifecycle/.
Bill Karwin
No offense meant, and did not mean to "harp", only to state that deployed instances of MySQL exist that would not support the answer I gave.
Larry Lustig
Fair enough. Yes, I agree that MySQL 4.1 is still the only version supported by some web hosting providers. Likewise, some people still use Microsoft SQL Server 2000, or Oracle 8.
Bill Karwin