使用sql server的时候遇到了一个类似这样的 text类型与int类型不兼容 如何才能正确关联到一起
后端我用的是python 前端用的vue
SELECT
*
FROM
book AS a
LEFT JOIN book_type AS b ON CONVERT(VARCHAR,a.type_id) = b.id
让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
用的是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步操作:
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
行转列
显示: