Jump to content

Recommended Posts

I need a help with selecting the rows in a table depending on the status in previous table.

Table1

Column1 	Column2		 Status
Smith	      Alex	                1
Smith         Mark		        0
John	      Smith		        1

 

 

I have second table with 2 columns. I want to select only those rows which have ANY of the user of table1 in column1 or column2 with status 1.

 

Table2

Column1		Column2		
Smith		  Anderson
Martin		  Walker
Alex		  Scott	

 

For example, Table1, the first row has status 1. Now i want to SELECT the rows from table2, which have "smith" OR "alex" in Column1 OR Column2. So, from Table2 it should select Row1 and Row3.

 

Do I have to join the tables? Wont that be slow?

Can I perform SELECT with EXISTS query?

 

Any help will be highly appreciated.

Link to comment
https://forums.phpfreaks.com/topic/205291-request-for-help-with-a-select-query/
Share on other sites

Yes, you need to JOIN the tables -- the speed will be depending on the indexes you choose and your version of mysql.  Easiest way to handle this is simply to UNION the various options:

 

( select * from table2 inner join table1 on ( table1.column1 = table2.column1 ) where table1.status = 1 )
UNION DISTINCT 
( select * from table2 inner join table1 on ( table1.column1 = table2.column2 ) where table1.status = 1 )
UNION DISTINCT 
( select * from table2 inner join table1 on ( table1.column2 = table2.column1 ) where table1.status = 1 )
UNION DISTINCT 
( select * from table2 inner join table1 on ( table1.column2 = table2.column2 ) where table1.status = 1 )

 

Of course, this makes me question your design.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.