Sunday, April 17, 2011

How can I select distinct rows when a text field is part of the returned fields in MS SQL Server 2000?

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?

From stackoverflow
  • 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)
    
  • 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
    
    Lieven : @Ekeko - That should be SELECT DISTINCT s.id.
    cdeszaq : Returns a row for every question.
    eKek0 : @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.
    cdeszaq : @Ekeko, without DISTINCT, it gives 1 row per question. With, it works correctly. It is necessary.
    eKek0 : @cdeszaq: That is what you want
    cdeszaq : @Ekeko: I am looking for section data for the **sections**, that have a question in them, not for section data for the questions themselves.
    Lieven : +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
  • 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
    

0 comments:

Post a Comment