有没有办法在 mysql 中使用 if else 表?
例子:
select * from tableA A, if(tableA.find=1,TableBA B,TableBB B) where A.id = B.aid
真实例子:
表是:location_order
、order_contract
、order_gm
、order_gm_hh
:
select *
from location order lo, order_contract oc, if(lo.hh=0,order_gm,order_gm_hh) as og
where lo.orderid = oc.orderid && oc.gmid = og.id
最佳答案
您可以 left outer join两个表,然后使用 IF()
SELECT
子句中的函数:
SELECT a.*,
IF(a.find = 1, b1.value, b2.value) b_value
FROM tableA a
LEFT JOIN tableBA b1 ON (b1.aid = a.id)
LEFT JOIN tableBB b2 ON (b2.aid = a.id);
测试用例:
CREATE TABLE tableA (id int, find int, value int);
CREATE TABLE tableBA (id int, aid int, value int);
CREATE TABLE tableBB (id int, aid int, value int);
INSERT INTO tableA VALUES (1, 1, 100);
INSERT INTO tableA VALUES (2, 0, 200);
INSERT INTO tableA VALUES (3, 1, 300);
INSERT INTO tableA VALUES (4, 0, 400);
INSERT INTO tableBA VALUES (1, 1, 10);
INSERT INTO tableBA VALUES (2, 3, 20);
INSERT INTO tableBB VALUES (1, 2, 30);
INSERT INTO tableBB VALUES (2, 4, 40);
结果:
+------+------+-------+---------+
| id | find | value | b_value |
+------+------+-------+---------+
| 1 | 0 | 100 | 10 |
| 2 | 1 | 200 | 30 |
| 3 | 0 | 300 | 20 |
| 4 | 1 | 400 | 40 |
+------+------+-------+---------+
4 rows in set (0.00 sec)
关于MySQL if/else 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4017797/