0
article_id cat_id
        70      7
        70      8
        71      9
        71      8

I need article_id where cat_id=8 and cat_id=7 and the result must return 70.

I tried this code but neither worked:

SELECT * 
FROM andishkadeh_article_catgory 
WHERE cat_id=6 AND cat_id=8

SELECT * 
FROM andishkadeh_article_catgory 
WHERE cat_id in (6,8)
4
  • Surely, you can see why a value can't be equal to 6 and 8 at the same time
    – Lamak
    Sep 8, 2016 at 19:03
  • I think I get what you want, but in your sample data, article_id 70 doesn't have cat_id 8 and 6
    – Lamak
    Sep 8, 2016 at 19:08
  • 3
    Please post examples of data as plain-text whenever possible. External screenshots are annoying and cannot be used as sample data for answers.
    – tadman
    Sep 8, 2016 at 19:15
  • SELECT article_id FROM my_table WHERE cat_id IN (7,8) GROUP BY article_id HAVING COUNT(*) = 2; and note that article_catgory_id is redundant, so I removed it. Your PRIMARY KEY would be formed on (article_id,cat_id)
    – Strawberry
    Sep 9, 2016 at 6:27

1 Answer 1

0

Ok, I think I understood the question. If you need to find the article_id that has 2 different rows with values for cat_id of 7 and 8, then you can do:

SELECT DISTINCT article_id 
FROM andishkadeh_article_catgory a
WHERE cat_id = 7
AND EXISTS(SELECT 1 FROM andishkadeh_article_catgory
           WHERE cat_id = 8
           AND article_id = a.article_id)
5
  • its work, but its depend to my category, for example if i insert new article_id with cat_id 8 than what i must to do
    – Buddha
    Sep 8, 2016 at 19:25
  • @Buddha I don't know, what do you want to happen if you insert a new article_id with cat_id 8?, if that same article_id doesn't also have a cat_id of 7, it won't be in the result
    – Lamak
    Sep 8, 2016 at 19:29
  • i want to filter my article depended to my category_id
    – Buddha
    Sep 8, 2016 at 19:39
  • @Buddha look, this does what you wanted, if you want something else, then you can ask another question or at least clarify this one
    – Lamak
    Sep 8, 2016 at 19:48
  • DISTINCT is surely redundant.
    – Strawberry
    Sep 9, 2016 at 6:24

Your Answer

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

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