如何从表中选择取决于另一个表列的值

时间:2015-09-21 04:42:14

标签: mysql sql

如何向sql发送selecttable语句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 = 0

如果transaction_idclaim.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 |

因此输出可能如下:

TLFMagicControl = class(TGraphicControl)

3 个答案:

答案 0 :(得分:2)

两个简单连接和简单过滤比一个复杂连接要好得多。

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' 

答案 1 :(得分:0)

我建议使用动态SQL查询。 这将使SQL运行逻辑更简单,易读且易于维护。

答案 2 :(得分:0)

我尝试指定并命名两个表中的每个列以进行匹配,并将retrieve表中缺少的列替换为NULL,如下所示:

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

现在对我有用。

有更好的方法吗?