簡體   English   中英

如何從表中選擇取決於另一個表列中的值

[英]How to select from table depend on value from another table column

如何使sql語句select哪個table取決於另一個table值,如下所示:

SELECT b.*, detail.*, t.date
FROM board AS b, transaction AS t,
 (CASE t.type
   WHEN 0 THEN (SELECT * FROM claim)
   WHEN 1 THEN (SELECT * FROM retrieve)
 END) AS detail
WHERE b.sn='D92AD006325' AND b.id=t.board_id AND detail.id=t.transaction_id

表的某些部分如下所示:

| board | |   transaction   | |   claim   | | retrieve |
|-------| |-----------------| |-----------| |----------|
| ...   | | board_id        | | id        | | id       |
|_______| | transaction_id  | | sender    | | code     |
          | type            | | location  | |__________|
          | date            | |___________|
          |_________________|

如果type = 0transaction_id裝置claim.id ,否則retrieve.id

所以輸出可能像這樣:

| board.id | ... | claim.id | claim.sender | location  | retrieve.id | retrieve.code |       date       |
|----------|-----|----------|--------------|-----------|-------------|---------------|------------------|
| 19       | ... | 10       | SenderA      | locationA |             |               | 10/09/2015 18:09 |
| 19       | ... |          |              |           | 8           | 58/03165      | 14/09/2015 11:10 |
| 19       | ... | 14       | SenderB      | locationA |             |               | 20/09/2015 08:10 |

兩個簡單的聯接和簡單的過濾器比一個復雜的聯接要好得多。

SELECT b.*, c.number, c.location, t.type, t.date
FROM board AS b, transaction AS t, claim AS c
WHERE b.sn='D92AD006325' AND b.id=t.board_id AND c.id=t.transaction_id AND t.type=0

UNION ALL

SELECT b.*, r.number, NULL AS location, t.type, t.date
FROM board AS b, transaction AS t, retrieve AS r
WHERE b.sn='D92AD006325' AND b.id=t.board_id AND r.id=t.transaction_id AND t.type=1

或者,使用外部聯接將兩個表聯接在一起,並在列中使用過濾器:

SELECT b.*, 
       case when t.type = 0 then c.number else r.number end as number, 
       case when t.type = 0 then c.location else null end as location, 
       t.type,
       t.date
FROM board AS b
INNER JOIN transaction AS t,
   ON (b.id=t.board_id)
LEFT OUTER JOIN claim c
   ON (c.id=t.transaction_id and t.type = 0)
LEFT OUTER JOIN retrieve r
   ON (r.id=t.transaction_id and t.type = 1)
WHERE b.sn='D92AD006325' 

我建議使用動態SQL查詢。 這將使SQL運行邏輯更簡單,易讀且易於維護。

我嘗試指定和命名兩個表中的每一列進行匹配,並使用NULL替換retrieve表中的缺失列,如下所示:

SELECT b.*, c.number, c.location, t.type, t.date
FROM board AS b, transaction AS t, claim AS c
WHERE b.sn='D92AD006325' AND b.id=t.board_id AND c.id=t.transaction_id AND t.type=0

UNION ALL

SELECT b.*, r.number, NULL AS location, t.type, t.date
FROM board AS b, transaction AS t, retrieve AS r
WHERE b.sn='D92AD006325' AND b.id=t.board_id AND r.id=t.transaction_id AND t.type=1

現在對我來說是工作。

還有更好的方法嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM