如果加入,SQLite会很棘手

时间:2011-08-03 19:24:05

标签: sql sqlite if-statement left-join

我有以下两个表:

T1(身份证,姓名) T2(id,hybrid_col)

如果hybrid_col是数字,我想做的是从T2中选择全部并使用T1选择JOIN。 基本上,hybrid_col包含对T1的id引用(在这种情况下我想从T1获取名称)或文本字符串(在这种情况下我只想要hybrid_col)。

我该怎么办呢?

谢谢。

4 个答案:

答案 0 :(得分:1)

如果我理解得很好,那应该是:

SELECT
(
  CASE 
     WHEN T2.HYBRID_COL = T1.ID THEN T1.NAME
      ELSE T2.HYBRID_COL
   END
) AS COLUMN
T2, T1
WHERE T2.ID = T1.ID
and ISNUMERIC(T1.HYBRID_COL ) = 1

编辑:不知道您是否在寻找ISNUMERIC,因为T1.ID是数字,如果是这种情况,只需删除它应该正常工作的and ISNUMERIC(T1.HYBRID_COL ) = 1,因为选择验证T2.HYBDRID_COL是否与T1.ID

匹配

答案 1 :(得分:1)

另一种方法是UNION这两种情况:

SELECT id, hybrid_col
FROM T2
WHERE hybrid_col+0!=hybrid_col
UNION
SELECT T2.id,t1.name
FROM T2 INNER JOIN T1 ON T2.hybrid_col=T1.id;

如果hybrid_col与T1.ID匹配,则无需检查hybrid_col是否为数字。如果T1.ID始终为数字,则非数字将被排除在连接之外。

编辑:要对它们进行排序,请封装结果并对其进行排序:

SELECT ID, VALUE
FROM
(
    SELECT id as "ID", hybrid_col as "Value"
    FROM T2
    WHERE hybrid_col+0!=hybrid_col
    UNION
    SELECT T2.id as "ID",t1.name as "Value"
    FROM T2 INNER JOIN T1 ON T2.hybrid_col=T1.id
) Q
ORDER BY ID;

还有其他方法,比如将结果传递到临时表并查询,但上面可能是最简单的单查询方法。

答案 2 :(得分:0)

尝试一次

select id,
(case when ISNUMERIC(hybrid_col) = 1 then name
else hybrid_col end) as custom_col
from
(select T2.id,T2.hybrid_col,T1.name from T2 left join T1 on T2.id = T1.id) mytab

答案 3 :(得分:0)

这应该不使用ISNUMERIC(在SQLite中不可用)

SELECT IFNULL(T1.name, T2.hybrid_col) AS [name]
FROM T2
    LEFT OUTER JOIN T1 ON CAST(T1.id AS VARCHAR) = T2.hybrid_col

这应该适合你,但是由于类型转换,你可能会失去索引所带来的任何好处,否则你可能会在T1.id