1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

MySQL WHERE AND OR - Can we use all three in one query?

Discussion in 'PHP' started by profs77, Aug 28, 2006.

  1. #1
    SELECT G.groupID, G.groupName
                 FROM `groups` G, `groupMembers` M
             WHERE M.userID = '$sessionUserID'
             OR M.userID = '$profileUserID'
             AND G.groupID = M.groupID
             GROUP BY M.groupID
             LIMIT 0,99;
    Code (SQL):
    Can AND and OR be used in one WHERE clause? What I'm trying to do is SELECT the list of group names that are shared between two users according to their userID. So one user would be viewing another users profile. $profileUserID and the user viewing would have a session variable $sessionUserID How do I make this work.
    SEMrush
     
    profs77, Aug 28, 2006 IP
    SEMrush
  2. wmtips

    wmtips Well-Known Member

    Messages:
    556
    Likes Received:
    47
    Best Answers:
    0
    Trophy Points:
    140
    #2
    Sure, OR and AND can be used together, but use brackets to group them. I think your query could be as follows (I think GROUP BY is not applicable):

    SELECT G.groupID, G.groupName
    FROM `groups` G, `groupMembers` M
    WHERE (M.userID = '$sessionUserID'
    OR M.userID = '$profileUserID')
    AND G.groupID = M.groupID
    LIMIT 0,99;
    Code (SQL):
     
    wmtips, Aug 29, 2006 IP
  3. ip076

    ip076 Peon

    Messages:
    79
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    0
    #3
    wmtips' query looks good! and he is right, the Group By is not needed. It is only used with the aggregate functions of mysql...like COUNT, SUM, etc...
     
    ip076, Aug 29, 2006 IP
  4. intelrate

    intelrate Peon

    Messages:
    31
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Yup. Brackets are not necessary if you remember that AND has bigger priority rather then OR. But query looks more clear if brackets exist.
     
    intelrate, Nov 21, 2008 IP