我可以从同一列中选择多个值吗
Posted
技术标签:
【中文标题】我可以从同一列中选择多个值吗【英文标题】:Can I SELECT more than one value from the same column 【发布时间】:2020-07-07 19:50:08 【问题描述】:我正在尝试使用单个 mysql.Data
SELECT
语句从不止一行中获取值。
我尝试使用以下代码但失败了。错误说
第 # 行有语法错误
MySqlConnection mysqlcon = new MySqlConnection(M_str_sqlcon);
MySqlCommand mysqlcom = new MySqlCommand(
"SELECT value FROM metatable WHERE(ProductID = 16 AND MetaKey = 'SKU') AND " +
"SELECT value FROM metatable WHERE(ProductID = 16 AND MetaKey = 'Price') AND " +
"SELECT value FROM metatable WHERE(ProductID = 16 AND MetaKey = 'Sold') AND " +
"SELECT value FROM metatable WHERE(ProductID = 16 AND MetaKey = 'SoldDate')"
, mysqlcon);
MySqlDataReader r = mysqlcom.ExecuteReader(CommandBehavior.CloseConnection);
prodMeta.Add(new ProductMeta
ProductSKU = r.GetString(0),
RegularPrice = r.GetDouble(1),
SoldCount = r.GetInt32(2),
SoldDate = r.GetString(3)
);
mysqlcon.Close();
【问题讨论】:
【参考方案1】:您可以像这样简单地使用in
运算符,而不是重复使用无效的Select
语句:
SELECT value
FROM metatable
WHERE ProductID = 16 AND MetaKey in ('SKU','Price', 'Sold', 'SoldDate')
而且你不需要 where 后面的括号。
【讨论】:
【参考方案2】:您可以将查询修改为 UNION 所有输出,如下所示。 Union 结合了 2 个或多个查询的结果(确保您具有相同顺序的相似列)
MySqlConnection mysqlcon = new MySqlConnection(M_str_sqlcon);
MySqlCommand mysqlcom = new MySqlCommand(
"SELECT value FROM metatable WHERE(ProductID = 16 AND MetaKey = 'SKU') UNION " +
"SELECT value FROM metatable WHERE(ProductID = 16 AND MetaKey = 'Price') UNION " +
"SELECT value FROM metatable WHERE(ProductID = 16 AND MetaKey = 'Sold') UNION " +
"SELECT value FROM metatable WHERE(ProductID = 16 AND MetaKey = 'SoldDate')"
, mysqlcon);
MySqlDataReader r = mysqlcom.ExecuteReader(CommandBehavior.CloseConnection);
prodMeta.Add(new ProductMeta
ProductSKU = r.GetString(0),
RegularPrice = r.GetDouble(1),
SoldCount = r.GetInt32(2),
SoldDate = r.GetString(3)
);
mysqlcon.Close();
但是,由于在此示例中您是从同一个表中提取数据,您可以使用 OR 来组合以下条件:
MySqlConnection mysqlcon = new MySqlConnection(M_str_sqlcon);
MySqlCommand mysqlcom = new MySqlCommand(
"SELECT value FROM metatable WHERE(ProductID = 16 AND MetaKey = 'SKU') OR (ProductID = 16 AND MetaKey = 'Price') OR (ProductID = 16 AND MetaKey = 'Sold') OR (ProductID = 16 AND MetaKey = 'SoldDate')"
, mysqlcon);
MySqlDataReader r = mysqlcom.ExecuteReader(CommandBehavior.CloseConnection);
prodMeta.Add(new ProductMeta
ProductSKU = r.GetString(0),
RegularPrice = r.GetDouble(1),
SoldCount = r.GetInt32(2),
SoldDate = r.GetString(3)
);
mysqlcon.Close();
或者您可以使用 IN 运算符,如下所示:
MySqlConnection mysqlcon = new MySqlConnection(M_str_sqlcon);
MySqlCommand mysqlcom = new MySqlCommand(
"SELECT value FROM metatable WHERE ProductID = 16 AND MetaKey IN ('SKU','Price','Sold','SoldDate')"
, mysqlcon);
MySqlDataReader r = mysqlcom.ExecuteReader(CommandBehavior.CloseConnection);
prodMeta.Add(new ProductMeta
ProductSKU = r.GetString(0),
RegularPrice = r.GetDouble(1),
SoldCount = r.GetInt32(2),
SoldDate = r.GetString(3)
);
mysqlcon.Close();
【讨论】:
以上是关于我可以从同一列中选择多个值吗的主要内容,如果未能解决你的问题,请参考以下文章