views:

558

answers:

3

I have a database-driven FAQ that is organised into sections and I am trying to get the section data for only those sections who have a question/answer associated with them.

Here is the schema:

|---------------------|      |----------------------|
|       Section       |      |       Quest-Ans      |
|---------------------|      |----------------------|
| PK | id(int)        |<--|  | PK     | id(int)     |
|    | title(varchar) |   |--| FK     | Sec_id(int) |
|    | desc(text)     |      |        | body(text)  |
|---------------------|      |----------------------|

When I try this query:

SELECT DISTINCT s.id, s.title, s.desc
FROM Section as s INNER JOIN Quest-Ans as q ON s.id = q.Sec_id

I get an error saying that DISCRETE cannot be applied to a text field. How can I get the data I want?

If it matters, this is an SQL2000 database.

EDIT:


Ok, so it seems like there are two ways to go about this. Either with EXISTS and a subquery in the where clause, or with the subquery in the inner join. Which is faster?

+4  A: 

This should do it:

SELECT s.id, s.title, s.desc
FROM Section as s 
WHERE EXISTS (SELECT * FROM Quest-Ans as q where q.Sec_id = s.id)
ck
A: 

Try it:

SELECT s.Title, s.Desc
FROM Section as s
INNER JOIN (
  SELECT DISTINCT s.id
  FROM Section as s 
  INNER JOIN Quest-Ans as q ON s.id = q.Sec_id
) q ON s.Id = q.Id
eKek0
@Ekeko - That should be SELECT DISTINCT s.id.
Lieven
Returns a row for every question.
cdeszaq
@Lieven: Select returns a set of rows, and a set has not repetead elements and inner join is done based on the key (I guess). So, distinct is not necessary.
eKek0
@Ekeko, without DISTINCT, it gives 1 row per question. With, it works correctly. It is necessary.
cdeszaq
@cdeszaq: That is what you want
eKek0
@Ekeko: I am looking for section data for the **sections**, that have a question in them, not for section data for the questions themselves.
cdeszaq
+1 This is the second time today I give an upvote because I completely disagree with whoever downvoated this reply. Besides a missing distinct, it was a correct answer
Lieven
+1  A: 
select s.id, s.title, s.desc
from Section s 
inner join (select distinct sec_id from Quest-Ans) dqa on s.id = dqa.sec_id
kristof