mysql仅在字段具有特定值的情况下才加入

时间:2018-12-13 06:45:17

标签: mysql join

我正在尝试在某些条件下通过连接获取表。我的桌子是:

        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       |
    -------------------------------------

我想将这些表加入:

  1. 如果tab_registrations.family不等于null,则从tab_family中选择相应的parent_id

    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. 如果tab_registrations.family等于“其他”,则选择tab_registrations.familyname和tab_registrations.parent_id

当我尝试以上查询时,如果tab_registrations.family ='others',则不会获取任何行

我该如何实现?谁能帮我吗?

2 个答案:

答案 0 :(得分:2)

LEFT JOIN不等于tab_registration.familyid的条件下更改为others。另外,您可以使用条件CASE..WHEN语句来获取familynameparent_id的值。

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

对于多表查询,如果更希望使用别名来提高代码的清晰度和可读性。

答案 1 :(得分:-2)

此查询可能有用

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