我正试图用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       |
    -------------------------------------

我想参加以下活动:
如果tab_registrations.family不等于空,则从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

如果tab_registrations.family等于'others',则选择tab_registrations.familyname和tab_registrations.parent_id
当我尝试上述查询时,如果tab_registrations.family='others',则不获取行
我怎样才能做到这一点?有人能帮我吗?

最佳答案

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

对于多表查询,为了代码的清晰性和可读性,最好使用别名。

关于mysql - mysql仅在字段具有特定值时才加入,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53756353/

10-10 10:40