haku Posted January 29, 2010 Share Posted January 29, 2010 I'm having troubles with a query. Table A: RID (int) VALUE (text) Table B: SID (int) RID (int) The tables are joined by RID. I want to select all rows from table A with a value of X, but not any that have a row in table B where SID = Y. My query now: SELECT rid FROM table_a JOIN table_b ON table_a.rid = table_b.rid WHERE table_a.value = "X" AND table_b.rid != Y The problem arises when there is another row in table_b that has that RID. So for example, lets say I don't want to return any rows with SID = 22, but in table_b I have: Row 1: RID = 1, SID = 22 Row 2: RID = 1, SID = 23 I don't want to select table_a.value for RID = 1, because there is a row with SID = 22 and RID = 1. But currently, my query will return the table_a.value for RID = 1, because of Row 2 in my example. Can anyone give me a hand with this? Thanks. Link to comment https://forums.phpfreaks.com/topic/190202-eliminating-results/ Share on other sites More sharing options...
haku Posted January 29, 2010 Author Share Posted January 29, 2010 Got it: SELECT table_1.value FROM table_1 LEFT JOIN table_2 ON table_1.rid = table_2.rid WHERE table_2.rid NOT IN (SELECT second.rid FROM {table_2} AS second WHERE second.sid = 22) Link to comment https://forums.phpfreaks.com/topic/190202-eliminating-results/#findComment-1003486 Share on other sites More sharing options...
oni-kun Posted January 29, 2010 Share Posted January 29, 2010 Got it: SELECT table_1.value FROM table_1 LEFT JOIN table_2 ON table_1.rid = table_2.rid WHERE table_2.rid NOT IN (SELECT second.rid FROM {table_2} AS second WHERE second.sid = 22) Good work. Almost was about to write an example down. Link to comment https://forums.phpfreaks.com/topic/190202-eliminating-results/#findComment-1003544 Share on other sites More sharing options...
kickstart Posted January 29, 2010 Share Posted January 29, 2010 Hi Possibly more efficient:- SELECT a.* FROM table_a LEFT OUTER JOIN (SELECT RID FROM table_b WHERE SID = 22) b ON a.RID = b.RID WHERE b.RID IS NULL All the best Keith Link to comment https://forums.phpfreaks.com/topic/190202-eliminating-results/#findComment-1003643 Share on other sites More sharing options...
haku Posted January 29, 2010 Author Share Posted January 29, 2010 Thanks mate - that definitely is more efficient. Link to comment https://forums.phpfreaks.com/topic/190202-eliminating-results/#findComment-1003752 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.