简体   繁体   中英

SQL not recognizing equal values

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?

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))

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM