在将 varchar 值 '1,2' 转换成数据类型 int 时失败。 (245)

问题遇到的现象和发生背景

使用sql server的时候遇到了一个类似这样的 text类型与int类型不兼容 如何才能正确关联到一起
后端我用的是python 前端用的vue

img

img

img

img

img

用代码块功能插入代码,请勿粘贴截图

SELECT
*
FROM
book AS a
LEFT JOIN book_type AS b ON CONVERT(VARCHAR,a.type_id) = b.id

运行结果及报错内容

img

我的解答思路和尝试过的方法

img


如果这样的话id= 2 的就没有内容了

我想要达到的结果

让id=2的内容正确显示出来

select a.id as bookId, GROUP_CONCAT(b.type SEPARATOR ',') as type from(
SELECT
    a.id,
    substring_index(
        substring_index(
            a.type_id,
            ',',
            b.help_topic_id + 1
        ),
        ',' ,- 1
    ) AS type_id
FROM
    book a
JOIN mysql.help_topic b ON b.help_topic_id < (
    length(a.type_id) - length(
        REPLACE (a.type_id, ',', '')
    ) + 1
)
)a left join book_type as b on a.type_id = b.id
group by a.id

img

用的是mssql

举个示例供你参考:
数据库:sql server
t1表的classid是text类型,要与t2表的id(int类型)做等值连接,即:

select * from table1 t1 left join table2 t2 on t1.classid = t2.id

直接这么写会报错,类型冲突
解决办法:是利用cast函数将这两个字段都转换成varchar类型,即:

select * from table1 t1 left join table2 t2 on cast(t1.classid as varchar(10)) = cast(t2.id as varchar(10))

'1,2' 和 id 本来就关联不起来啊,你是想'1,2' 和谁关联起来

设计有问题,多个ID应该分成子表,查询果走索引,效率高。
如果按现在的设计,有两个办法,第一个是是用string_split一类的函数拆分出来再关联,另外一个是用charindex判断是否存在,判断时book的typeid前后加逗号,book_type表的id转类型后前后也加逗号,可防止查2时出来2222一类的。

参考链接,希望有帮助

根据截图看,关系是 1对多显示。至少需要2步操作:

  1. 先匹配 book表 中 type_id 在 book_type中每条记录(一对多关系):
SELECT a.*, b.type
  FROM 表book AS a
  LEFT JOIN 表book_type AS b
    ON charindex(',' + convert(VARCHAR, b.id) + ',', ',' + a.type_id + ',') > 0

关于charindex() 函数用法 https://www.cnblogs.com/lip-blog/p/7243729.html

  1. 在第1步的基础上,进行 行转列 显示:
    https://www.dandelioncloud.cn/article/details/1482837886566477825