问题
select art.artno, art.name from Art
left outer join store on art.artno =store.artno
where art.Artno not in (select art.artno from store)
The query is supposed to be like this but seems not working(I do not get any result rows beside the column names). Using a MSSQL 2008.
table art table store EXPECTED RESULT
artno name artno qty artno name
1 xbox360 1 1 2 XHW
2 XHW 3 2 5 PS2
3 NETANDO 4 1
5 PS2 6 3
6 PS1
4 X1
How do I write a query to get the Expected out shown in the example?
Just to let you know the tables are 100plus K rows large if helps.
Finally some lights on why the above code does not work would be beneficial. I looked at this this link seems that outer join must work, may be I could not understand this at all.
I tried with full outer join
as well, did not help. Using except
I was able to find just the artno
but did not let me produce the name
column.
回答1:
another approach could be
select
a.`artno`,
a.`name`
from
art a
left join
store s on s.artno=a.artno
where
s.artno is null
On large tables, the second approach would most likely be better.
回答2:
select art.artno, art.name from art
where art.artno not in (select store.artno from store)
You don't need to do any kind of join to use an inner query (the (select store.artno from store)
in this case). The inner query is like building a temporary table, filling it with values, and using it in the query.
Since you want your inner query to give you all artno
in the table store
, you should use (select store.artno from store)
and not (select art.artno from store)
, since I think that would select the art.artno
from the outer query, without taking into account the contents of the store
table.
回答3:
Georges answer works, but on tables of that size a correlated subquery with a 'not exists' will be quicker.
Tested, my subqueries were slower than left outer. It's the way forward
来源:https://stackoverflow.com/questions/11863643/how-do-i-return-two-columns-from-first-table-if-only-one-column-partially-matche