简体   繁体   English

SQL:此“ where if”查询有什么问题?

[英]SQL: whats wrong with this “where if” query?

I've selected table: A1 and joined A2 to A1 , AND A3 joined to A2 . 我选择了表: A1并将A2联接到A1 ,而A3联接到A2
A1 .level and A2 .level always not null A1 .level和A2 .level始终不为null
A3 .level means that that joined row is null. A3 .level表示连接的行为null。
A1 .level is bigger then A2 .level. A1 .level大于A2 .level。
IF A3 .level is smaller than A2 .level or setted to (NULL) 如果A3 .level小于A2 .level或设置为(NULL)
SO, I need result like this 所以,我需要这样的结果

╔══════════╦══════════╦══════════╗
║ A1.level ║ A2.level ║ A3.level ║
╠══════════╬══════════╬══════════╣
║        3 ║        2 ║ 1        ║
║       14 ║       10 ║ 5        ║
║       15 ║       13 ║ (NULL)   ║
╚══════════╩══════════╩══════════╝

I've tried to write statement like this 我试图写这样的声明

SELECT A1.level, A2.level, A3.level
FROM A1,
LEFT JOIN A2 ON A1.parentID = A2.id
LEFT JOIN A3 ON A2.parentID = A3.id
WHERE A1.level > A2.level
      AND A2.level > A3.level OR A3.level IS NULL

but it doesn't work. 但这不起作用。 How to write IF (or CASE) statment for this? 如何为此编写IF(或CASE)语句? Thanks 谢谢

You need to add parentheses: 您需要添加括号:

SELECT A1.level, A2.level, A3.level
FROM A1
JOIN A2  -- no need for LEFT JOIN
  ON A1.parentID = A2.id
LEFT JOIN A3
  ON A2.parentID = A3.id
WHERE (A1.level > A2.level)
      AND (A2.level > A3.level OR A3.level IS NULL)

Otherwise the order of precedence is: 否则,优先顺序为:

NOT - AND - OR

Use parenthesis; 使用括号;

SELECT A1.level, A2.level, A3.level
FROM A1,
LEFT JOIN A2 ON A1.parentID = A2.id
LEFT JOIN A3 ON A2.parentID = A3.id
WHERE 
    (A1.level is not null and A2.level is not null) and --A1.level and A2.level always not null
    (A1.level > A2.level) and --A1.level is bigger then A2.level.
    (A2.level > A3.level OR A3.level IS NULL) --A3.level is smaller than A2.level or setted to (NULL)

I think you made a copy/paste error (you specify the field to select after the from) and put a comma at the wrong place (before your first join). 我认为您犯了一个复制/粘贴错误(您在from之后指定了要选择的字段),并在错误的位置(第一次加入之前)添加了一个逗号。 Furthermore, you need parenthesis for your condition concerning A3. 此外,对于与A3有关的条件,您需要括号。 I personally don't think that a IF statement is required in this case. 我个人认为在这种情况下不需要IF语句。

SELECT A1.level, A2.level, A3.level 
FROM A1
LEFT JOIN A2 ON A1.parentID = A2.id
LEFT JOIN A3 ON A2.parentID = A3.id
WHERE A1.level > A2.level
      AND (A2.level > A3.level OR A3.level IS NULL)

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

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