Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using OR and AND in MySQL

Tags:

php

mysql

I have a query as follow: (shows are a table with tv shows and IMDB ID and recommended_titles is a table with two columns with IMDB_ID)

Select t2.* from shows t, shows t2, recommended_titles WHERE 
t.imdb_id = recommended_titles. title_id_1 
AND recommended_titles.title_id_2=t2.imdb_id 
AND t.imdb_id = 0367279 LIMIT 7

The query is fine but I realized that it was only checking in the first column for my imdb id when it can also appear in my second one. So i try to add the following:

OR
recommended_titles.title_id_2=t.imdb_id 
AND t.imdb_id = recommended_titles. title_id_1 
AND t.imdb_id = 0367279 LIMIT 7

But apparently OR can't be used with AND,

any suggestions as how I should do this ?

Edit: To explain what I'm trying to do, here's a quick example in case my explanations above are too confusing. table shows has rows like this:

name of a tv show | 00001
name of another   | 00002
name of another   | 00003

table recommended titles has (notice that an ID can be in either column)

00001 |  00002
00002 |  00003
like image 982
Callombert Avatar asked Nov 22 '25 15:11

Callombert


1 Answers

You may look at operator precedence in mysql (and see that AND has an higher precedence than OR), or use parenthesis (much easier to use and maintain)

(t.imdb_id = recommended_titles.title_id_1 OR
recommended_titles.title_id_2=t.imdb_id)

AND recommended_titles.title_id_2=t2.imdb_id 
AND t.imdb_id = 0367279 LIMIT 7
like image 70
Raphaël Althaus Avatar answered Nov 24 '25 03:11

Raphaël Althaus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!