sql中的条件连接

时间:2016-06-11 14:04:47

标签: mysql sql oracle

我想在依赖于某个条件的字段上加入两个表:

struct sockaddr_storage

select * from table1 join table2 on table1.$variable = table2.id

我可以这样做吗?

4 个答案:

答案 0 :(得分:2)

有几种方法可以解决这个问题

IF()
IFNULL(),
COALESCE(),
CASE

使用IF

SELECT * FROM table1 JOIN table2 ON 
IF(table1.id1 IS NOT NULL,table1.id1, table1.id2)=table2.id;

使用IFNULL

SELECT * FROM table1 JOIN table2 ON 
IFNULL(table1.id1, table1.id2)=table2.id;

使用COALESCE

SELECT * FROM table1 JOIN table2 ON 
COALESCE(table1.id1, table1.id2)=table2.id;

使用案例

SELECT * FROM table1 JOIN table2 ON 
(CASE 
WHEN table1.id1 IS NULL THEN table1.id2
ELSE table1.id1 
END) = table2.id;

参考 http://sqlfiddle.com/#!9/8076eb/4

答案 1 :(得分:1)

您可以在JOIN中使用条件和OR:

// Register type
DateTime newdt = DateTime.ParseExact(ConfigurationManager.AppSetting["businessDate"], "dd/MM/yyyy", CultureInfo.InvariantCulture);

YourContainer.RegisterInstance<DateTime>("newdt", newdt); 


YourContainer.RegisterType<Calculator>(new InjectionConstructor(YourContainer.Resolve<DateTime>("newdt")));

答案 2 :(得分:1)

select * 
from table1 join table2 
    on case when table1.id1 is not null then table1.id1 else table1.id2 end = table2.id

答案 3 :(得分:1)

`select * from table1,table2 where ifnull(table1.id1,table1.id2)=table2.id`

如果ifnull中的第一个值为null,则它使用第二个值。

再见