在我的数据库中,我有两个表:
1. "subjects" table: that include 2 fileds:
*id, *desctiption,
2. "subSubjects" table that include 4 fileds:
*id, *Desctiption, *subject_id, *department_id (primary key of departments table).
我需要返回每个主题都包含匹配主题列表的主题列表, 有一种方法可以在不使用 select inside select 语句的情况下做到这一点吗? (加入或其他声明)? *我有一个类-“主题”,其中包含子主题的数组列表。
View 中的结果需要是这样的:
*****************************
subject * sub-subject * dep *
*****************************
sub_1 * sub sub1 * 1 *
*********************
* sub sub2 * 2 *
*****************************
sub_2 * sub sub 4 * 1 *
*****************************
sub_3 * sub sub 3 * 1 *
*********************
* sub sub 5 * 2 *
*********************
* sub sub 6 * 2 *
*****************************
最佳答案
使用以下查询:
SELECT
CASE WHEN t.id = (SELECT TOP 1 id -- Sub query
FROM Subsubjects t3
WHERE t3.subject_id = t.subject_id
ORDER BY t3.id) THEN q.description
ELSE ''
END AS Subjects, t.description AS Subsubjects, t.department_id
FROM Subsubjects t
LEFT JOIN subjects q ON q.id = t.subject_id
ORDER BY t.id
它会返回预期的数据如下:
*****************************
subject * sub-subject * dep *
*****************************
sub_1 * sub sub1 * 1 *
*********************
* sub sub2 * 2 *
*****************************
sub_2 * sub sub 4 * 1 *
*****************************
sub_3 * sub sub 3 * 1 *
*********************
* sub sub 5 * 2 *
*********************
* sub sub 6 * 2 *
*****************************
以下是我们如何使用 sql 查询处理列表对象的示例:
public List<Product> GetAllProducts() //GetAllProducts() is a list-type method
{
Query = "SELECT * FROM Products";
Command = new SqlCommand(Query, Connection);
Connection.Open();
Reader = Command.ExecuteReader();
List<Product> products = new List<Product>(); //Created a list
while (Reader.Read())
{
Product product = new Product(); //Created an object from the class
product.ProductId = Convert.ToInt32(Reader["ProductID"]);
product.CategoryId = Convert.ToInt32(Reader["CategoryID"]);
product.ProductName = Reader["ProductName"].ToString();
product.Details = Reader["Details"].ToString();
product.Price = (double)Reader["Price"];
product.Stock = Convert.ToDouble(Reader["Stock"]);
products.Add(product); //Finally bind the object with the list
}
Reader.Close();
Connection.Close();
return products;
}
关于mysql - 从数据库中获取项目列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39346621/