SQLite if join 很棘手
我有以下两个表:
T1(id,name) T2 (id,hybrid_col)
我想要做的是从 T2 中选择所有内容,如果 Hybrid_col 是数字,则与 T1 联接。 基本上,hybrid_col 保存对 T1 的 id 引用(在这种情况下我想从 T1 获取名称)或文本字符串(在这种情况下我只想要hybrid_col)。
请问我该怎么做?
谢谢。
I have the following two tables:
T1 (id,name)
T2 (id,hybrid_col)
What I want to do is select all from T2 and JOIN with T1 if hybrid_col is numeric.
Basically, hybrid_col holds an id reference to T1 (in which case I want to get the name from T1) or a text string (in which case I just want hybrid_col).
How can I do that please?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
另一种方法是仅对两种情况进行 UNION:
如果与 T1.ID 匹配,则无需检查 Hybrid_col 是否为数字。如果 T1.ID 始终为数字,则非数字将被排除在连接之外。
编辑:要对它们进行排序,封装结果并对其进行排序:
还有其他方法,例如将结果管道到临时表中并进行查询,但上面可能是最简单的单查询方法。
Another approach is to just UNION the two cases:
There is no need to check if hybrid_col is numeric if it has a match with T1.ID. If T1.ID is always numeric, non-numerics will be left out of the join.
EDIT: To sort them, encapsulate the result and sort that:
There are other ways, like piping the result into a temp table and querying that, but the above is probably the simplest one-query approach.
如果我理解得很好,这应该是:
编辑: 不知道您是否在寻找 ISNUMERIC,因为 T1.ID 是数字,如果是这种情况,只需删除
和 ISNUMERIC (T1.HYBRID_COL ) = 1
无论如何它应该可以工作,因为选择验证了T2.HYBDRID_COL
与T1.ID
匹配If I understood well, this should be:
Edit : Don't know if you were looking for the ISNUMERIC because the T1.ID is numeric, if it is that case just remove the
and ISNUMERIC(T1.HYBRID_COL ) = 1
it should work anyway because the select validates that theT2.HYBDRID_COL
matches with theT1.ID
尝试一次
Try this once
这应该在不使用 ISNUMERIC 的情况下工作(这在 SQLite 中不可用)
这应该对您有用,但由于类型转换,您可能会失去在 T1.id 上可能拥有的索引带来的任何好处
This should work without using ISNUMERIC (which is unavailable in SQLite)
This should work for you, but due to the type cast you will likely lose any benefits from indexing that you might otherwise have on T1.id