仅当字段具有特定值时才使用mysql连接

jdg4fx2g  于 2021-06-17  发布在  Mysql
关注(0)|答案(2)|浏览(215)

我正试图用join在某些条件下获取表。我的table是:

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\u registrations.family不等于null,则从tab\u family中选择相应的父级\u 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

如果tab\u registrations.family等于“others”,则选择tab\u registrations.familyname和tab\u registrations.parent\u id
当我尝试上面的查询时,如果tab\u registrations.family='others',则不会获取任何行
我怎样才能做到这一点?有人能帮我吗?

mnemlml8

mnemlml81#

可能对这个查询有用

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
xe55xuns

xe55xuns2#

更改为 LEFT JOIN 条件是 tab_registration.familyid 不等于 others . 此外,还可以使用条件 CASE..WHEN 声明以获取 familyname 以及 parent_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

对于多表查询,最好使用别名以提高代码的清晰度和可读性。

相关问题