2013-02-20 31 views
-1

我有一個表的列id,product_type,product_id,數量都是整數。 我需要根據product_type從其他表中選擇數據。例如。如果product_type爲0,則從tableA中選擇,如果product_type爲1,則從tableB等中選擇。我嘗試找到解決方法如何創建select但未成功。有人能幫助我嗎。我感謝每一個幫助。謝謝。SQLite從基於列值的多表中選擇

+3

請編輯您的帖子,包括你的企圖在解決方案中的一個。謝謝。 – bernie 2013-02-20 16:39:11

+1

更多信息。請顯示錶結構並列出您想要在結果集中看到的列。 – 2013-02-20 16:39:33

+2

通常,當您需要執行動態選擇源表的查詢時,這表明您的數據庫設計存在缺陷。顯示完整的數據庫設計,也許我們可以提供幫助。 – JohnFx 2013-02-20 16:46:28

回答

3

將主表與各個產品表連接起來,但使用左連接並在連接條件中包含product_type = x過濾器,以便僅實際連接所需的記錄。

這會導致很多NULL值;使用​​3210獲得非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 ... 
+0

我很想把它變成一個視圖,然後我可以做簡單的選擇... – 2013-02-20 21:54:13

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 

大概可以使用加入,但將取決於您的架構更有效率。

+0

我認爲OP希望從'TableA'中選擇多個字段,'TableB'取決於'table'中的product_type,而不僅僅是一個字段 – Saju 2013-02-20 16:55:15

+0

然後多個CASE語句。 – 2013-02-20 17:05:24