selecting data from a table with a query

Discussion in 'Databases' started by guitarbinge, Aug 7, 2008.

  1. #1
    Hello

    I have a table like this:

    ID p1 p2 p3
    -- --- --- ---
    1 22 33 44
    2 55
    3 66 77

    Im trying to write a query that will output :

    ID Phone
    -- -------
    1 22
    1 33
    1 44
    2 55
    3 66
    3 77


    Thank you
     
    guitarbinge, Aug 7, 2008 IP
  2. live-cms_com

    live-cms_com Notable Member

    Messages:
    3,128
    Likes Received:
    112
    Best Answers:
    0
    Trophy Points:
    205
    Digital Goods:
    1
    #2
    Google 'sql join', joins might be able to do it.
     
    live-cms_com, Aug 7, 2008 IP
  3. andrewgjohnson

    andrewgjohnson Active Member

    Messages:
    180
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    53
    #3
    Learn how to normalize your database.
     
    andrewgjohnson, Aug 7, 2008 IP
  4. mwasif

    mwasif Active Member

    Messages:
    816
    Likes Received:
    23
    Best Answers:
    1
    Trophy Points:
    70
    #4
    Use UNION ALL
    SELECT id, p1 AS Phone FROM table
    UNION ALL
    SELECT id, p2 FROM table
    UNION ALL
    SELECT id, p3 FROM table
    ORDER BY id
    Code (markup):
     
    mwasif, Aug 8, 2008 IP
  5. wardz

    wardz Peon

    Messages:
    34
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    nice tips and trick, thx.
    but...
    for the same case maybe you have to add for "select distinct"
     
    wardz, Aug 8, 2008 IP
  6. mwasif

    mwasif Active Member

    Messages:
    816
    Likes Received:
    23
    Best Answers:
    1
    Trophy Points:
    70
    #6
    Good point wardz. You can achieve this if you do not use ALL with UNION

    SELECT id, p1 AS Phone FROM table
    UNION 
    SELECT id, p2 FROM table
    UNION 
    SELECT id, p3 FROM table
    ORDER BY id
    Code (markup):
     
    mwasif, Aug 9, 2008 IP