SQLite:FROM部分中的CASE

时间:2014-06-04 08:08:02

标签: sqlite case

如果表格中不存在 UserID = 7 ,我需要选择 MCU 表。请帮帮我,我做错了什么?

SELECT
    MCUs.MCUID
FROM
  CASE 
    WHEN ReqMCUDevs.UserID = 7 THEN
       MCUs

       INNER JOIN MCUDevs
        ON MCUs.MCUID = MCUDevs.MCUID

       INNER JOIN ReqMCUDevs
        ON MCUDevs.DevID = ReqMCUDevs.DevID
         AND ReqMCUDevs.Quantity >= MCUDevs.Quantity
    ELSE
       MCUs
  END

如果 UserID = 7 存在

,我需要重新分配此查询
SELECT
    MCUs.MCUID
FROM
    MCUs

    INNER JOIN MCUDevs
     ON MCUs.MCUID = MCUDevs.MCUID

    INNER JOIN ReqMCUDevs
     ON MCUDevs.DevID = ReqMCUDevs.DevID
     AND ReqMCUDevs.Quantity >= MCUDevs.Quantity
WHERE
    ReqMCUDevs.UserID = 7

和此查询,如果不是

SELECT
    MCUs.MCUID
FROM
    MCUs

数据库架构:
database schema

最简单的解决方案是使用两个不同的查询

db = sqlite3.connect("..\\DB.db", isolation_level = None);
c = db.cursor()
#...

c.execute("SELECT UserID FROM ReqMCUDevs WHEN UserID = ?", (UserID,))

if c.fetchall() == []:
    c.execute("SELECT MCUID FROM MCUs")
else:
    c.execute("""SELECT MCUID FROM MCUDevs
JOIN ReqMCUDevs ON MCUDevs.DevID = ReqMCUDevs.DevID
    AND ReqMCUDevs.Quantity <= MCUDevs.Quantity
WHERE ReqMCUDevs.UserID = ?""", (UserID,))

但它确实不是答案

1 个答案:

答案 0 :(得分:0)

CASE仅适用于表达式(即计算值);无法有条件地更改查询的基本结构。

但是,有不同的机制来获得你想要的东西。

首先,带有连接的查询实际上并没有从连接表中返回任何内容,因此可以使用子查询重写它:

SELECT Name,
       Price
FROM MCUs
WHERE MCUID IN (SELECT MCUID
                FROM MCUDevs
                JOIN ReqMCUDevs ON MCUDevs.DevID = ReqMCUDevs.DevID
                               AND ReqMCUDevs.Quantity >= MCUDevs.Quantity
                WHERE ReqMCUDevs.UserID = 7)
ORDER BY Price

现在,如果子查询为空,我们希望忽略此WHERE过滤器。 这可以通过单独检查来完成:

SELECT Name,
       Price
FROM MCUs
WHERE MCUID IN (SELECT MCUID
                FROM MCUDevs
                JOIN ReqMCUDevs ON MCUDevs.DevID = ReqMCUDevs.DevID
                               AND ReqMCUDevs.Quantity >= MCUDevs.Quantity
                WHERE ReqMCUDevs.UserID = 7)
   OR NOT EXISTS (SELECT MCUID
                  FROM MCUDevs
                  JOIN ReqMCUDevs ON MCUDevs.DevID = ReqMCUDevs.DevID
                                 AND ReqMCUDevs.Quantity >= MCUDevs.Quantity
                  WHERE ReqMCUDevs.UserID = 7)
ORDER BY Price