简体   繁体   English

MySQL在LEFT JOIN表达式内更改列

[英]MySQL change column inside LEFT JOIN expression

I'm trying to use different columns based on their values. 我正在尝试根据其值使用不同的列。 If column A is null then use column B. The thing is, this is inside a LEFT JOIN expression: 如果列A为空,则使用列B。问题是,它在LEFT JOIN表达式内:

SELECT *
FROM 
  novinarji
  LEFT JOIN naslovi ON novinarji.stalniNaslovId=naslovi.id
  LEFT JOIN posta ON naslovi.postaId=posta.id
WHERE
  posta.stPoste = 3000

I need novinarji.stalniNaslovId to change to novinarji.zacasniNaslovId when the first column is NULL . 当第一novinarji.zacasniNaslovId NULL时,我需要novinarji.stalniNaslovId更改为novinarji.zacasniNaslovId

I hope this is clear enough. 我希望这足够清楚。

Thank you! 谢谢!

You do not necessarily need to use onyl literal column names in a joining ON condition necessarily. 您不一定需要在联接ON条件中使用onyl文字列名称。 The join's ON condition needs to result in a truthful boolean expression. 联接的ON条件需要产生一个真实的布尔表达式。 You can therefore use COALESCE() in the join condition to return the preferred column or the alternate if the preferred is NULL . 因此,可以在COALESCE()条件中使用COALESCE()返回首选列,如果首选为NULL则返回备用列。

-- Careful with SELECT * in a join query...
-- better to be specific about the needed column names
SELECT *
FROM 
  novinarji
  -- COALESCE() will return stalniNaslovId if non-null, and zacasniNaslovId otherwise
  LEFT JOIN naslovi 
    ON COALESCE(novinarji.stalniNaslovId, novinarji.zacasniNaslovId) = naslovi.id
  LEFT JOIN posta 
    ON naslovi.postaId=posta.id
    -- Move this condition to the ON clause, otherwise it turns
    -- your LEFT JOIN into an INNER JOIN if filtered in the WHERE
    AND post.stPoste = 3000

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM