Link to home
Start Free TrialLog in
Avatar of Geoff Sutton
Geoff SuttonFlag for Canada

asked on

MySQL Query problem on join

I have a simple query running against MySQL through PHP.  I want to insert into a table all values that are in another table but not in that table.  This is the query I have:

INSERT Into DataNew (CollectorCode,CollectGross)
SELECT DISTINCT DataHistory.CollectorCode, 0
FROM DataHistory
LEFT OUTER JOIN DataNew ON DataNew.CollectorCode = DataHistory.CollectorCode
WHERE DataHistory.CodeType =1
AND DataHistory.CollectorCode NOT LIKE '%-b'
AND DataNew.CollectorCode IS NULL

The trouble is that the select query returns 602 rows whether I fileter by the DataNew.CollectorCode is Null or not.  How can I go about insertings into DataNew all Collectorcodes from DataHistory which are not already present?
Avatar of pivar
pivar
Flag of Sweden image

Hi,

I would do like this (if CollectorCode is unique)

INSERT Into DataNew (CollectorCode,CollectGross)
SELECT DISTINCT dh.CollectorCode, 0
FROM DataHistory dh
WHERE NOT EXISTS (SELECT 1 FROM DataNew dn WHERE dn.CollectorCode = dh.CollectorCode)

/peter
Avatar of Geoff Sutton

ASKER

Unfortunately that does not work.  You query:
SELECT DISTINCT dh.CollectorCode, 0
FROM DataHistory dh
WHERE NOT EXISTS (SELECT 1 FROM DataNew dn WHERE dn.CollectorCode = dh.CollectorCode) AND
dh.CodeType=1
Returns the exact same results as
SELECT DISTINCT dh.CollectorCode, 0
FROM DataHistory dh
WHERE dh.CodeType=1

 They both show 602 rows, and datanew has 149 distinct codes entered.  I was reasonably sure that the SQL and the logic were good.  But being unfamiliar with MySQL I am wondering if the comparisons pay attention to potential trailing spaces and hidden characters?  I know that the collation is case insensitive.
Thanks for the quick response.  Hopefully we can resolve this right away.
Geoff
 
ASKER CERTIFIED SOLUTION
Avatar of pivar
pivar
Flag of Sweden image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial