简体   繁体   中英

SQL THREE TABLE QUERY FORMATION

I have 3 tables

table a             table b                        table c
+--------+          ---------+-------            ------+-------+
| ID     |              ID  | STATUS|             ID  | STATUS|
+--------+         ---------+--------            -----+--------+
| 1      |              4   |  A    |              6  | A
| 2      |              5   | NULL  |              5  |NULL
| 3      |              1   | A     |              3  | A
| 9      |              2   | NULL  |              1  | NULL

Now I want a record from TABLE B and C which matches TABLE A ID

I wrote an query

SELECT DISTINCT ID 
FROM
  (SELECT a.ID,b.STATUS FROM A a B b where a.ID=b.ID
   UNION
   SELECT a.ID,C.STATUS 
   FROM A a,C C 
   WHERE a.ID=C.ID) as T

it returns 3 records

but when I append where condition T.STATUS='A'

SELECT DISTINCT ID 
FROM
  (SELECT a.ID,b.STATUS FROM A a B b
   WHERE a.ID=b.ID
   UNION
   SELECT a.ID,C.STATUS 
   FROM A a,C C 
   WHERE a.ID=C.ID) as T 
WHERE T.STATUS='A'

it returns 2 records

again I changed WHERE condition as T.STATUS is null

SELECT DISTINCT ID FROM
 (SELECT a.ID,b.STATUS 
  FROM A a,B b
  WHERE a.ID=b.ID
  UNION 
  SELECT a.ID,C.STATUS
  FROM A a,C C
  WHERE a.ID=C.ID) as T
WHERE T.STATUS is null

it returns 2 records

totally 4 RECORDS but my first query without where condition it returns 3

How this mismatch? I know its my query problem but

I want to apply my where condition to only 3 records(query without where condition returns result).

You are selecting distinct id . id = 1 has rows with both 'A' and NULL . The results make sense.

I would write the query as:

SELECT DISTINCT ID
FROM (SELECT a.ID, b.STATUS
      FROM A a JOIN
           B b 
           ON a.ID=b.ID 
      UNION
      SELECT a.ID, C.STATUS
      FROM A a JOIN
           C C 
      WHERE a.ID = C.ID
     ) T

Note that your original query had at least one syntax error. You should learn proper explicit join syntax. Simple rule: Never use commas in the from clause.

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