Reputation: 1345
UPDATE: I figured out a large part of what caused my problem. When I queried the database to find the data type, it correctly returned CHAR(4) for t2.sale_code.
However, the GUI did not display leading zero's. t3.sale_code did not have leading zeros in the file that populated the table. That's what caused my confusion and I corrected the zero problem. Now it joins without any CAST or other manipulation.
__________________________________________________I have a query:
SELECT
t1.id, t2.sale_code, t3.sale_code, t3.title
FROM
t1
INNER JOIN t2 ON t1.id = t2.id
INNER JOIN t3 ON t3.id = t2.id
There are some different one-to-many relationships that I can't control that induce duplication. I need to do this:
WHERE
t2.sale_code = t3.sale_code
However, this just won't work. I'm not sure what I'm doing wrong. I can manually make it work:
SELECT
t1.id, t2.sale_code, t3.sale_code, t3.title
FROM
t1
INNER JOIN t2 ON t1.id = t2.id
AND t2.dt > t1.dt_active
AND t2.dt < t1.dt_inactive
INNER JOIN t3 ON t3.id = t2.id
WHERE
t2.sale_code = 4
AND t3.sale_code = 4
For example, this returns a proper matched pair of sale_code
's. However, when I compare them directly (`WHERE t2.sale_code = t3.sale_code) it returns no results. Am I doing something wrong here?
Upvotes: 0
Views: 485
Reputation: 19469
If they are both character/string types, then you should be quoting them like
sale_code = '4'
There is likely some bit of data in the column that is not visible, but is getting truncated by the auto cast of int to varchar(4).
You can either use DATALENGTH() to determine if the column has hidden chars, or copy the value into a decent text editor and look at the value in hex view.
A dirty way to get the join to work is to wrap the sale_code with trims, but you are better off cleaning your data.
RTRIM(LTRIM(t2.sale_code)) = RTRIM(LTRIM(t3.sale_code))
Upvotes: 2
Reputation: 449
Can you just add to your inner join
SELECT
t1.id, t2.sale_code, t3.sale_code, t3.title
FROM
t1
INNER JOIN t2 ON t1.id = t2.id
INNER JOIN t3 ON t3.id = t2.id AND t2.sale_code = t3.sale_code
Upvotes: 0