-2

please can anyone help me, I am familiar with PHP but I'm not good in it.please help. I have two table and both have id, see sample,

Table1

----------------------------------
   **ID**   |   **NAME**     |   **AGE**    |
----------------------------------
  001   |   john     |    21     |
----------------------------------
  002   |   erik     |    18     |
----------------------------------
  003   |   ella     |    19     |
----------------------------------
and soon...

Table2

----------------------------------
   **ID**   |   **SUBJECT**     |   **GRADE**    |
----------------------------------
  001   |   math     |    80     |
----------------------------------
  003   |   english     |    83     |
----------------------------------
and soon....

here is the problem, I just want to select a row from table1 were its id dont match in table2.

I used this condition but it wont work the way I expected to so that means this is wrong,

if($t1_id!=$t2_id){
blah blah blah...
}
else
{
all data is match!
}

when an id in table2 matched in table1 it already show that my data is all match even if there is only one entry in table2.

Please help me. If you don,t understand how I show my problem please tell me,THANK YOU!.

Tab Alleman
  • 31,483
  • 7
  • 36
  • 52
Frank
  • 13
  • 3
  • try this as your query : `select * from table1,table2 where table1.id=table2.id` , this query only find users that have grade –  Mar 07 '16 at 13:22
  • @MohsenShakibafar your solution will only find matches(that is not what is being asked for). You are using a method which is more than 20 years old to join your tables – t-clausen.dk Mar 07 '16 at 13:28
  • @t-clausen.dk you right , yeah its 20 years old , better practice was `join` only want to check what he exactly want :) –  Mar 07 '16 at 13:35
  • Possible duplicate of [How to select rows with no matching entry in another table?](http://stackoverflow.com/questions/4076098/how-to-select-rows-with-no-matching-entry-in-another-table) – Tab Alleman Mar 07 '16 at 13:50

2 Answers2

0

You can use exists clause to check whether a record is present in another table, e.g.

select * 
from table1 t1
where t1.id = ?
and exists(
 select * 
 from table2 t2 
 where t2.id = t1.id;
);
Darshan Mehta
  • 30,102
  • 11
  • 68
  • 102
0

These 2 solutions will work in sqlserver:

Solution 1:

SELECT
  t1.ID, t1.NAME, t1.AGE
FROM
  table1 t1
LEFT JOIN
  table2 t2
ON t1.ID = t2.ID
WHERE t2.ID is null

Solution 2:

SELECT
  ID, NAME, AGE
FROM
  table1 t1
WHERE NOT EXISTS(SELECT * FROM table2 WHERE t1.ID = ID)
t-clausen.dk
  • 43,517
  • 12
  • 59
  • 92
  • this is great! Thank you sir t-clausen.dk! solution 2 works great!..thank you so much.. – Frank Mar 07 '16 at 13:45