当以不同顺序收到相同字符串时,如何与字符串进行比较?
例如:在我的表中有两列名为"meaning","Relevant name"
列数据类型位于varchar
含义 - 相关名称
food - snacks;choco;chips
输入 - " choco;chips;snacks "
输出 - "food"
如何比较这种类型的字符串?任何人都可以提出任何想法
答案 0 :(得分:0)
将CSV数据放入列中是不好的;关系数据库并未设计为以这种方式处理。为您的值设置多行:
Meaning|RelName
food |snacks
food |choco
food |chips
在查询时拆分输入:
SELECT DISTINCT Meaning FROM t WHERE RelName IN ('choco','chips','snacks')
分割和查询形成应该以您的前端语言
完成不要使用字符串连接来构建带有值的SQL,即这种天真的方式(c#语法):
//this is bad - forming a list of values by replacing ; with',' and concatting
//into anotehr sql string
strSQL = "SELECT DISTINCT Meaning FROM t WHERE RelName IN ('" + input.Replace(";", "','") + "')";
将参数与字符串连接一起使用:
//this is good
//declare the base sql stub
sqlCommand.CommandText = "SELECT DISTINCT Meaning FROM t WHERE RelName IN (";
//split the input into values
var foods = input.Split(';');
//for each value
for(int i = 0; i < foods.Length; i++){
//add a bit to the sql with a new parameter named
sqlCommand.CommandText += "@param" + i + ",";
//add a parameter name and value to match the just-added parameter
sqlCommand.Parameters.AddWithValue("param" + i, foods[i]);
}
//the sql ends with a comma; a syntax error. trim it and put a ) to close the IN
sqlCommand.CommandText = sqlCommand.CommandText.TrimEnd(',') + ")";