Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a query with intersect equivalent to those 'where a and b'?

Tags:

sql

postgresql

I have a DB with postgresql and I wrote two simple queries

select page from title where word = 'france' and part = 'headline';

and

select page from title where word = 'france' 
intersect 
select page from title where part = 'headline';

I think they should return the same result but actually it's different. Any suggestions?

The table structure is simply id, word, page, part.

EDIT:

I tried also

select distinct

but the query with intersect always returns some non relevant results. This is a DB of a simple reverse table of some web news pages. So page, word and part are not unique. But no duplicated entries.

like image 323
darkjh Avatar asked Feb 22 '23 23:02

darkjh


2 Answers

WHERE (a) AND (b) is a boolean condition applied to Every record. A record only gets included if it satisfies the whole condition. In other words, only records where word is 'france' AND part is 'headline' at the same time will be included.


Is what you need more similar to using an OR in your condition?

select page from title where word = 'france' or part = 'headline';


Or are you having problems due to there being multiple records referencing the same page?

For example...

1 | 'france'  | 'aaa' | 'headline'
2 | 'france'  | 'bbb' | 'body'
3 | 'germany' | 'bbb' | 'headline'

'aaa' will be returned by both your queries.

'bbb' will be returned by only your second query.

like image 134
MatBailie Avatar answered Feb 24 '23 12:02

MatBailie


The only technical difference I see is that intersect operation would generate unique pages. The first may generate duplicates.

Update: They aren't the same. the correct answer is what Dems already explained(I voted his answer):

page  word     part
1     france   headline
2     uk       headline
2     france   body

word = france AND part = headline => page 1

word = france => page 1, 2 part = headline => page 1, 2

intersection of previous two sets => page 1, 2

Update2: Response to question: how to make intersect give the same result? The intersect must be done over column in conditions, as here.

select page, word, part from title where word = 'france' 
intersect 
select page, word, part from title where part = 'headline'
like image 29
Florin stands with Ukraine Avatar answered Feb 24 '23 12:02

Florin stands with Ukraine