简体   繁体   中英

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

I've selected table: A1 and joined A2 to A1 , AND A3 joined to A2 .
A1 .level and A2 .level always not null
A3 .level means that that joined row is null.
A1 .level is bigger then A2 .level.
IF A3 .level is smaller than A2 .level or setted to (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? 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). Furthermore, you need parenthesis for your condition concerning A3. I personally don't think that a IF statement is required in this case.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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