如何检索SQL Server中一个表的任何字段中不存在的数据?

时间:2017-03-25 12:46:14

标签: sql sql-server stored-procedures

我想检索Table1

中任何字段中不存在的数据

例如 我有两张桌子

1。 #tempLastSold

2。 ItemRelation

#tempLastSold记录

ID      ExtendedDescription  StoreID
160641  FA012                1400      //ID present in ID of ItemRelation 
160641  FA012                2001      //ID present in ID of ItemRelation 
160632  FA003                1400      //ID present in ChildID3 of ItemRelation 
160632  FA003                2001      //ID present in ChildID3 of ItemRelation 
156824  25298                2001      //ID present in ID of ItemRelation 
158430  161-18-132           1302      //ID present in ChildID2 of ItemRelation 
  

注意 #tempLastSold 的ID可能出现在 ItemRelation的任何字段(可能是 ID,ChildID1,ChildID2,ChildID3)

ItemRelation记录

ID       ChildID1       ChildID2       ChildID3
160641   160642         Null           Null
160631   160634         160633         160632       
156824   Null           Null           Null 
158433   158431         158430         Null 
1        1A             1B             1C
2        2A             2B             2C
2        3A             3B             3C

我想显示 #tempLastSold

中不存在的 ItemRelation 的记录

#tempLastSold 拥有数百万条记录,

ItemRelation 拥有30,000个recorsds

我试过这段代码

select ir.ID,
    ir.ItemLookupCode,
    ir.ChildID1,
    ir.ChildItemLookupCode1,
    ir.ChildID2,
    ir.ChildItemLookupCode2,
    ir.ChildID3,
    ir.ChildItemLookupCode
FROM [HQMatajer].[dbo].[ItemRelation] ir
left join #tempLastSold tLs on tLs.ID != ir.id 
left join #tempLastSold tLs1 on tLs1.ID !=ir.ChildID1 
left join #tempLastSold tLs2 on tLs2.ID !=ir.ChildID2
left join #tempLastSold tLs3 on tLs3.ID != ir.ChildID3

但它检索的记录超过60,000。

4 个答案:

答案 0 :(得分:2)

这是你想要的吗?

select ir.*
from ItemRelation ir 
where not exists (select 1
                  from #tempLastSold tls
                  where tls.id = ir.id
                 ) or
      (ir.childid1 is not null and
       not exists (select 1
                   from #tempLastSold tls
                   where tls.id = ir.childid1
                  )
      ) or
      (ir.childid2 is not null and
       not exists (select 1
                   from #tempLastSold tls
                   where tls.id = ir.childid2
                  )
      ) or
      (ir.childid3 is not null and
       not exists (select 1
                   from #tempLastSold tls
                   where tls.id = ir.childid3
                  )
      );

为了提高性能,您需要3tempLastSold(id)上的索引。

您还可以将查询简化为:

select ir.*, g.which
from ItemRelation ir cross join
     (values (id, 'id'), (childid1, 'childid1'), (childid2, 'childid2'), (childid3, 'childid3')) v(id, which)
where v.id is not null and
      not exists (select 1
                  from #tempLastSold tls
                  where tls.id = ir.id
                 );

这可以轻松显示缺少哪一列。

编辑:

您也可以使用left join表达此信息。逻辑有点棘手。您需要查找匹配项,然后查看不匹配的位置。对于id列,这看起来像:

select ir.*
from ItemRelation ir left join
     #tempLastSold tls
     on tls.id = ir.id
where tls.id is null;

您的版本会找到所有非NULL值的匹配项,因为tls中始终会有一条与给定值不匹配的记录(非NULL )价值。

答案 1 :(得分:1)

使用单个public class SearchActivity extends AppCompatActivity { private Socket socket; public ArrayList<SearchResultUser> searchResultUsers; public SearchAdapter searchAdapter; public RecyclerView rvSearchResults; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); setUpConnectionToServer(); searchResultUsers = new ArrayList<>(); searchAdapter = new SearchAdapter(searchResultUsers); rvSearchResults = (RecyclerView)findViewById(R.id.rvSearchResults); RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this); rvSearchResults.setLayoutManager(mLayoutManager); rvSearchResults.setItemAnimator(new DefaultItemAnimator()); rvSearchResults.setAdapter(searchAdapter); rvSearchResults.addOnItemTouchListener(new RecyclerTouchListener(this, rvSearchResults, new RecyclerViewClickListener() { @Override public void onClick(View view, int position) { } @Override public void onLongClick(View view, int position) { } })); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } private void setUpConnectionToServer() { try { socket = IO.socket("http://youripaddress:3000"); } catch (URISyntaxException e) { throw new RuntimeException(e); } socket.connect(); socket.on("search", searchListener); } private Emitter.Listener searchListener = new Emitter.Listener(){ @Override public void call(final Object... args){ runOnUiThread(new Runnable() { @Override public void run() { //clear current search result set searchResultUsers.clear(); searchAdapter.notifyDataSetChanged(); //get new search result JSONArray jsonArray = (JSONArray)args[0]; try { //loop through all new search results for(int i = 0; i < jsonArray.length(); i++){ //for every new search result create JSON object JSONObject jsonObject = jsonArray.getJSONObject(i); //from every JSON object create SearchResultUser model object SearchResultUser mySearchResultUser = new SearchResultUser(jsonObject.getInt("id"), jsonObject.getString("name")); //add every new SearchResultUser model object to the array list searchResultUsers.add(mySearchResultUser); } } catch (JSONException e) { e.printStackTrace(); } //notify the adapter of data set change searchAdapter.notifyDataSetChanged(); } }); } }; @Override protected void attachBaseContext(Context base) { super.attachBaseContext(CalligraphyContextWrapper.wrap(base)); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_search, menu); // Associate searchable configuration with the SearchView // SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search_activity)); // searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); searchView.setOnQueryTextListener(onQueryTextListener); return super.onCreateOptionsMenu(menu); } public SearchView.OnQueryTextListener onQueryTextListener = new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { //Toast.makeText(SearchActivity.this,"search query => " + query, Toast.LENGTH_LONG).show(); //socket.emit("search",query); return false; } @Override public boolean onQueryTextChange(String newText) { //Toast.makeText(SearchActivity.this,"newText query => " + newText, Toast.LENGTH_SHORT).show(); socket.emit("search",newText); if(newText.equals("")){ searchResultUsers.clear(); searchAdapter.notifyDataSetChanged(); } return false; } }; @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_search_activity) { Log.d("test","clicked on search"); return true; } return super.onOptionsItemSelected(item); } } public class SearchResultUser { private int id; private String name; public SearchResultUser() { } public SearchResultUser(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } public class SearchAdapter extends RecyclerView.Adapter<SearchAdapter.MyViewHolder> { private ArrayList<SearchResultUser> searchResultUserList; public class MyViewHolder extends RecyclerView.ViewHolder { public ImageView ivProfileSearchResult; public TextView tvUserNameSearchResult; public MyViewHolder(View view) { super(view); ivProfileSearchResult = (ImageView) view.findViewById(R.id.ivProfileSearchResult); tvUserNameSearchResult = (TextView) view.findViewById(R.id.tvUserNameSearchResult); } } public SearchAdapter(ArrayList<SearchResultUser> searchResultUserList) { this.searchResultUserList = searchResultUserList; } //this doen't work public void update(ArrayList<SearchResultUser> searchResultUserList){ this.searchResultUserList.clear(); for (SearchResultUser searchResultUser: searchResultUserList) { this.searchResultUserList.add(searchResultUser); } notifyDataSetChanged(); } @Override public SearchAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.search_result_item, parent, false); return new SearchAdapter.MyViewHolder(itemView); } @Override public void onBindViewHolder(SearchAdapter.MyViewHolder holder, int position) { SearchResultUser searchResultUser = searchResultUserList.get(position); holder.tvUserNameSearchResult.setText(searchResultUser.getName()); } @Override public int getItemCount() { return searchResultUserList.size(); } }

left join

rextester 演示http://rextester.com/SBA83066

返回:

select ir.ID,    
    ir.ChildID1,    
    ir.ChildID2,   
    ir.ChildID3
from [dbo].[ItemRelation] ir
  left join #tempLastSold tLs 
    on tLs.ID = ir.id 
    or tLs.ID = try_convert(int,ChildID1) 
    or tLs.ID = try_convert(int,ChildID2)
    or tLs.ID = try_convert(int,ChildID3)
where tls.id is null;

使用+----+----------+----------+----------+ | ID | ChildID1 | ChildID2 | ChildID3 | +----+----------+----------+----------+ | 1 | 1A | 1B | 1C | | 2 | 2A | 2B | 2C | | 2 | 3A | 3B | 3C | +----+----------+----------+----------+ 代替相同的结果

not exists()

答案 2 :(得分:0)

您可以不在

中使用
select * from #tempLastSold where ID not in (select id from ItemRelation Union all Select childid1 from ItemRelation union all Select childid2 from itemrelation union all select childid3 from ItemRelation )

答案 3 :(得分:0)

您的问题不是很清楚,您想要检索第1号表格中不再存在的内容吗? 按表号2? 或者您希望表1通过某些信息复制到表2?