Selecting a subset...

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Asteras

    #1

    Selecting a subset...

    This is my Table Tb that has a composite key (ID and Pr are both
    Primary Keys):

    ID | Pr
    1 | A
    1 | B
    1 | C
    2 | B
    3 | A
    4 | A
    4 | C
    5 | C

    What query do I need to do to get a list of those Identities (ID) that
    have the Property (Pr) A and NOT the Property B, ie 3 and 4?

  • Markus Popp

    #2
    Re: Selecting a subset...

    select ID from Tb where Pr = 'A' - or
    select ID from Tb where Pr != 'B' (if any value except B should be listed)
    or
    select distinct ID from Tb where Pr != 'B' (if every ID should show up only
    once).

    But I think what you meant is best represented by the first query ;-).

    Markus


    Comment

    • Bill Karwin

      #3
      Re: Selecting a subset...

      Asteras wrote:[color=blue]
      > This is my Table Tb that has a composite key (ID and Pr are both
      > Primary Keys):
      >
      > ID | Pr
      > 1 | A
      > 1 | B
      > 1 | C
      > 2 | B
      > 3 | A
      > 4 | A
      > 4 | C
      > 5 | C
      >
      > What query do I need to do to get a list of those Identities (ID) that
      > have the Property (Pr) A and NOT the Property B, ie 3 and 4?[/color]

      SELECT Tb1.ID
      FROM Tb AS Tb1 LEFT OUTER JOIN Tb AS Tb2
      ON Tb1.ID = Tb2.ID AND Tb2.Pr = 'B'
      WHERE Tb1.Pr = 'A' AND Tb2.ID IS NULL

      Regards,
      Bill K.

      Comment

      • Markus Popp

        #4
        Re: Selecting a subset...

        Oups, seems, I got you wrong.

        Here I have another solution:

        SELECT distinct a.id
        from tb a
        where (select count(*) from tb b where pr='a' and a.id = b.id) > 0
        and (select count(*) from tb c where pr='b' and a.id = c.id) = 0

        .... but Bill's way to solve it with an outer join might be better, because
        it also works with MySQL < 4.1.

        Markus


        Comment

        • Asteras

          #5
          Re: Selecting a subset...

          Markus and Bill,

          Thank you for your advice. Both your solutions produced the same
          correct output.

          Ioannis

          Comment

          Working...