在SQL中防止重复的结果 [英] Prevent duplicate results in SQL

查看:98
本文介绍了在SQL中防止重复的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用程序中列出了来自我的SQL数据库的catagories的组合框( comboBox1 )。它正在拉动数据正确的时刻。我唯一的问题是,当数据列在组合框中,有重复的结果。例如:



我想要的列表:

 示例1 
示例2
示例3

>

示例1
示例1
示例1
示例1
示例1
b示例2
示例2
示例2
示例3
示例3
示例3

这里是我用来列出数据的代码:

  void ListCat()
{
DataTable linkcat = new DataTable(linkcat);
using(SqlConnection sqlConn = new SqlConnection(@Connection stuff;))
{
using(SqlDataAdapter da = new SqlDataAdapter(SELECT name FROM list WHERE name< '',sqlConn))
{
da.Fill(linkcat);
}
}
foreach(linkcat.Rows中的DataRow da)
{
comboBox1.Items.Add(da [0] .ToString());
}
}

总之,我的问题是如何防止重复的数据被列出?

解决方案

使用 DISTINCT



将您的查询更改为

  SELECT DISTINCT name FROM list WHERE name<> 'NULL'

假设您可能已存储字符串值 NULL



如果您的名称中包含 real NULL 字段,您的查询应该像这样

  SELECT DISTINCT名称FROM list WHERE名称不为NULL 


I have a combo box (comboBox1) in my application that lists catagories from my SQL database. It is pulling the data correctly at the moment. My only problem is that when the data is listed in the combo box, there are duplicate results. For example:

What I want it to list:

Example 1
Example 2
Example 3

What it actualy lists:

Example 1
Example 1
Example 1
Example 1
Example 1
Example 2
Example 2
Example 2
Example 3
Example 3
Example 3

Here is the code that I am using to list the data:

public void ListCat()
{
DataTable linkcat = new DataTable("linkcat");
using (SqlConnection sqlConn = new SqlConnection(@"Connection stuff;"))
{
using (SqlDataAdapter da = new SqlDataAdapter("SELECT name FROM list WHERE name <> 'NULL'", sqlConn))
{
da.Fill(linkcat);
}
}
foreach (DataRow da in linkcat.Rows)
{
comboBox1.Items.Add(da[0].ToString());
}
}

In short, my question would be how can I prevent duplicate data from being listed?

解决方案

Use DISTINCT . It will eliminate the duplicate records.

Change your query to

SELECT DISTINCT name FROM list WHERE name <> 'NULL'

Assuming you may have stored the string value NULL inside your name column for some records.

If you have the real NULL in the name field, your query should be like this

SELECT DISTINCT name FROM list WHERE name is not NULL

这篇关于在SQL中防止重复的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆