aliaktas
aliaktas

Reputation: 165

mysql nested select statement

I am newbie for relational tables. As i learn more, i see many advantages of sql statement. However i stuck on some point.

i look for if can get a single table for desired data-set from 5 tables. One of the table named 'eta' is used to connect other 4 tables.

Aim: A phone number or email can be used by many users, and users may also have multiple phone number or email address. I want to list the phone numbers or email addresses with the user name that uses them.

Sample Data: Please check http://sqlfiddle.com/#!2/60acce for the table structure and sample data-set

The final expected final result for the phone case as follow:

  phone            name    extra
  45336467      ABC Co.   
  45336467      Gery      114
  45336467      Todd      117
  45336467      Adam      119

Thanks

Edit: Explanation for the table relation.

table 'eta' has 4 fields which have table relations. column 'own' shows the company, person etc value 'f' for company and 'k' for person others will used for different tables

v1_id for id of own field's referred table..

column 'res' refers to email and phone tables. value 't' for phone and 'e' for email. v2_id for id of res field's referred table

Upvotes: 2

Views: 1201

Answers (1)

newfurniturey
newfurniturey

Reputation: 38456

After filing through your schema, I believe the following query should work for you:

SELECT
    phone.tel AS phone,
    CASE WHEN person.name IS NULL THEN company.titles ELSE person.name END AS name,
    eta.extra AS extra
FROM
    eta
    LEFT JOIN person
        ON eta.v1_id = person.id
        AND eta.own = 'k'
    LEFT JOIN company
        ON eta.v1_id = company.id
        AND eta.own = 'f'
    JOIN phone
        ON phone.id = eta.v2_id
WHERE
    eta.res = 't'

This assumes that eta.res = 't' if the relationship is to the "phone" table. Also, eta.own = 'k' for people, eta.own = 'f' for companies.

It uses two left joins to pull from the person/company tables so that it can accomplish the pulls in a single query. If the person.name column is null, that means the current record is from the company table and will select that value instead (for the name column).

The same can be done to select the email addresses (assuming eta.res = 'e' to relate to the email table):

SELECT
    email.email AS email,
    CASE WHEN person.name IS NULL THEN company.titles ELSE person.name END AS name
FROM
    eta
    LEFT JOIN person
        ON eta.v1_id = person.id
        AND eta.own = 'k'
    LEFT JOIN company
        ON eta.v1_id = company.id
        AND eta.own = 'f'
    JOIN email
        ON email.id = eta.v2_id
WHERE
    eta.res = 'e'

Upvotes: 3

Related Questions