我正在尝试将MySQL查询转换为MsSql查询,但我遇到了麻烦。这是我的疑问:
MySQL
SELECT *,
(SELECT count(books.id)
FROM books
WHERE books.status = 1
AND FIND_IN_SET(categories.id, books.multiple_category_id)) AS book_count
FROM categories, books
WHERE categories.parent_id=0
AND categories.status=1 ;
SQL我试过
SELECT *,
(SELECT count(books.id)
FROM books
WHERE books.status = 1
AND CHARINDEX(categories.id, books.multiple_category_id) > 0) AS book_count
FROM categories, books
WHERE categories.parent_id=0
AND categories.status=1 ;
我得到的错误是:
Argument data type int is invalid for argument 1 of charindex function.
供参考。 http://sqlfiddle.com/#!3/4ed19/3
有没有人有任何想法? 提前谢谢!
答案 0 :(得分:3)
使用此查询。我刚刚在这里改变了CAST(categories.id AS VARCHAR)
。因为id
在integer
表中是categories
。
SELECT *,
(SELECT count(books.id)
FROM books
WHERE books.status = 1
AND CHARINDEX(CAST(categories.id AS VARCHAR), books.multiple_category_id) > 0) AS book_count
FROM categories,
books
WHERE categories.parent_id=0
AND categories.status=1 ;
答案 1 :(得分:1)
这是另一种方法
SELECT *,
(SELECT Count(books.id)
FROM books
WHERE books.status = 1
AND ',' + books.multiple_category_id + ',' LIKE '%,' + cast(categories.id as varchar(50))+ ',%') AS book_count
FROM categories,
books
WHERE categories.parent_id = 0
AND categories.status = 1;
注意:您的查询中categories
和books
表之间有一个笛卡尔积。我猜你在books
子句中不需要From
。停止在列中存储逗号分隔值,这违反了第一范式
答案 2 :(得分:1)
MS-SQL
' CHARINDEX函数需要VARCHAR或NVARCHAR作为参数,因此您的categories.id应转换为VARCHAR。像这样:
CHARINDEX(CAST(categories.id AS VARCHAR(16)), books.multiple_category_id ) > 0 )
但是,我会考虑重构表和您的查询:
<强> 1。查询重构
如上所述,您可以进行错误匹配。例如。 categories.id = 1
而您的multiple_category_id
是'11,12'
。另一种选择是split your string是这样的条件:
AND EXISTS (SELECT 1 FROM dbo.SplitString(books.multiple_category_id) WHERE Token = categories.id)
此外,*应该替换为实际需要的列(在这种情况下,它将带来两个表中的所有列)。像这样:
<强> 2。表格重构
您应该像这样定义一个X表,而不是解析字符串:
categoryId FK引用类别 bookId FK参考书 PRIMARY KEY(categoryId,bookId)
所以,您可以使用简单的JOIN
来代替字符串搜索来执行查询,这可能会更慢(不能使用索引)。