Jump to content

I need a smart select query, help on this one.


csueiras

Recommended Posts

Greetings,

 

I have a table with only two columns, a ctd_id and a dt_id. The ctd_id is the key that is auto_incremented. What happens is that I need a select that is able to give me a list of all the dt_id that are common to a certain range of ctd_id's. Like, lets suppose I want all the dt_id's that ctd_id=1, ctd_id=20 and ctd_id=34 have in common.

 

Right now I have this query:

select DISTINCT dt_id from ctd_data where ctd_id='1' OR ctd_id='2' OR ctd_id='4'

(I want the common dt_ids to ctd_id=1, ctd_id=2 and ctd_id=4)

 

The problem with that query is that it gives me all the dt_id's that those rows have, except they are not repeated. Any help on this would be greatly appreciated.

 

 

Christian

Link to comment
Share on other sites

You have to self join the table, but it's not that simple, as the query you need relies on how many ctd_id's values you choose.

This should work for the case you posted:

select distinct a.dt_id from ctd_data a join ctd_data b on (a.dt_id = b.dt_id and a.ctd_id='1' and b.ctd_id='2') join ctd_data c on (a.dt_id = c.dt_id and a.ctd_id='1' and c.ctd_id='4')

The matter is if you have less or more than 3 values, this query doesn't fit

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.