根据第一个表中的字段从其他表中进行条件选择

时间:2016-07-14 04:23:47

标签: mysql

我有一张包含销售数据的表格和一个定义所售商品类型的字段,其中item_sold可以有两个值:'i'和'u'

表销售

sale_no  item_type   item_id
123         i         111
124         i         945
125         u         345
126         u         777
......

项目的描述在另外两个表格中......这是必要的......由于下面未显示的其他字段,项目信息不能在不同项目类型的同一个表格中....

表item_i

item_id    item_description    Other Fields.....
 111         Some random text description
 945         ......

表item_u

item_id    item_description    Other Fields....
 345         Some random text description
 777         ......

我想做的是这个(伪代码)

SELECT sales.*
 IF item_type = i
  Select item_i.* (sales and item_i are joined on item_id)
 ELSE IF item_type = u
  SELECT item_u.* (sales and item_u are joined on item_id)
WHERE sales.sale_no = some_sale_no

我已经阅读了一些指向SELECT with CASE语句的答案但是我无法构造查询.....简而言之我正在寻找这个:

SELECT * FROM table A
AND depending on tableA.some_field value
 select * from table B OR select * from table C
where table A.sale_no = 123

最终结果是一行:

sale_no   item_type   item_id   item_description    other_fields_from_either_item_i/u

1 个答案:

答案 0 :(得分:1)

我认为你不一定需要在这里使用CASE声明。相反,只需将两个项目表加入sales,然后使用COALESCE()显示不是NULL的说明:

SELECT s.sale_no,
       s.item_type,
       COALESCE(i1.item_description, i2.item_description, 'No description available')
FROM sales s
LEFT JOIN item_i i1
    ON s.item_id = i1.item_id
LEFT JOIN item_u i2
    ON s.item_id = i2.item_id
WHERE s.sale_no = 123

即使在您希望拥有2个以上项目表的情况下,COALESECE仍应完成工作,假设您只希望一个连接表具有非NULL描述。< / p>

Click here是一个讨论MySQL COALESECE()功能如何运作的好网站。

<强>更新

我认为某个项目只能在item_iitem_u中输入,但不能同时包含两者。如果两者都有条目,那么您可以尝试以下SELECT语句:

SELECT s.sale_no,
       s.item_type,
       COALESCE(i1.item_description, 'No item_i description available'),
       COALESCE(i2.item_description, 'No item_u description available')