mysql nested query on same table

Discussion in 'MySQL' started by meloncreative, Apr 7, 2010.

  1. #1
    Hey all

    So I have a generic content table, which is used for pages etc. some of these pages have parent / child relationships so I need to write a query that will grab info from both of them.

    The ci_catid is a type of page which controls what is parent and child.

    ci_link is a unique identifier so part of a URL can extract a specific page

    $q = "SELECT *, (SELECT ci_id FROM content_items WHERE ci_link = '$link') AS parent_id FROM content_items WHERE ci_catid = '1' AND ci_category = '$type' AND ci_title = parent_id";
    PHP:
    Gets
    Any ideas? Is nested queries a really bad way to do this? (i am rubbish with JOINs)
     
    meloncreative, Apr 7, 2010 IP
  2. meloncreative

    meloncreative Peon

    Messages:
    37
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    turns out aliases dont work in WHERE clauses, needed to use HAVING instead
     
    meloncreative, Apr 8, 2010 IP
  3. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #3
    I think I would try something like this:

    $q = "
    SELECT * FROM content_items
    WHERE ci_title IN (SELECT ci_id FROM content_items WHERE ci_link = '$link')
    AND ci_catid = '1' AND ci_category = '$type'";
     
    jestep, Apr 8, 2010 IP