SQLite根据列值从多个表中进行选择

时间:2013-02-20 16:36:33

标签: sql sqlite

我有一个包含列id,product_type,product_id,数量全部为整数的表。 我需要根据product_type从另一个表中选择数据。例如。如果product_type为0,则从tableA中选择,如果product_type为1,则从tableB等中选择。我试图找到解决方案如何创建选择但不成功。有谁可以帮助我吗。我感谢每一个帮助。谢谢。

2 个答案:

答案 0 :(得分:3)

使用单个产品表加入主表,但使用左连接并在连接条件中包含product_type = x过滤器,以便实际只连接所需的记录。

这会产生许多NULL个值;使用coalesce获取输出的非NULL值:

SELECT sales.id,
       sales.quantity,
       sales.product_type,
       coalesce(tableA.name, tableB.name) AS name,
       coalesce(tableA.color, tableB.color) AS color,
       tableA.numberOfAs                -- is NULL for other product types
FROM sales
  LEFT JOIN tableA ON sales.product_type = 0 AND
                      sales.product_id = tableA.product_id
  LEFT JOIN tableB ON sales.product_type = 1 AND
                      sales.product_id = tableB.product_id
WHERE ...

答案 1 :(得分:0)

听起来你需要一个CASE声明

SELECT 
   CASE 
      WHEN product_type = 1 THEN (SELECT column FROM table1 WHERE ...)
      WHEN product_type = 2 THEN (SELECT column FROM table2 WHERE ...)
   END 
FROM table

使用JOINS可能会提高效率,但这取决于您的架构。