Aishwaryas
Aishwaryas

Reputation: 643

mysql join only if a field has a particular value

I am trying to fetch a table on certain conditions with join. My table is:

        tab_registrations
    --------------------------------------------
    reg_id |familyid| familyname  | parent_id |
           |        |             |           |
    -------|--------|-------------|-----------|
    1      |  2     |   null      | null      |
    -------|--------|-------------|-----------|
    2      | others |    abc      | 3         |
    -------|--------|-------------|-----------|
    3      | 3      |   null      |   null    |
    -------|--------|-------------|-----------|
    4      | others |  def        |   2       |
    -------|--------|-------------|-----------|

    tab_family
    -------------------------------------
    family_id | family_name | parent_id |
              |             |           |
    -------------------------------------
    1         | tyu         |   0       |
    -------------------------------------
    2         | xyz         |   1       |
    -------------------------------------
    3         | mno         |   2       |
    -------------------------------------

I want to join these tables on:

  1. if tab_registrations.family not equal to null, then select corresponding parent_id from tab_family

    SELECT tab_registration.*,tab_family.family_id,tab_family.parent_id
     FROM `tab_registration`
     join tab_family  on tab_registration.family_id = tab_family.family_id
     WHERE reg_id = 1
    
  2. if tab_registrations.family is equal to 'others', then select tab_registrations.familyname and tab_registrations.parent_id

When I try the above query if tab_registrations.family = 'others', no rows fetched

How can I achieve this? Can anyone help me?

Upvotes: 3

Views: 2287

Answers (2)

Chirag
Chirag

Reputation: 313

may be useful this query

SELECT tr.*,tf.family_id,tf.parent_id,
 IF(tr.familyid='others',tr.familyname,tf.family_name) as fname
 IF(tr.familyid='others',tr.parent_id,tf.parent_id) as parentId
 FROM `tab_registration` tr
 left join tab_family tf on tr.family_id = tf.family_id

Upvotes: -2

Madhur Bhaiya
Madhur Bhaiya

Reputation: 28834

Change to LEFT JOIN with the condition that tab_registration.familyid is not equal to others. Also, you can use conditional CASE..WHEN statements to get the familyname and parent_id values.

SELECT tr.*,
       CASE WHEN tr.familyid = 'others' THEN tr.familyname 
            ELSE tf.family_name
       END AS familyname, 
       CASE WHEN tr.familyid = 'others' THEN tr.parent_id 
            ELSE tf.parent_id
       END AS parent_id
FROM tab_registration tr
LEFT JOIN tab_family tf
  ON tr.family_id = tf.family_id AND 
     tr.familyid <> 'others'
WHERE tr.reg_id = 1

For multi-table queries, it if preferable to use Aliasing for code clarity and readability.

Upvotes: 4

Related Questions