简体   繁体   中英

How to join multiple with one query on SQLIte3

Here are my case:

  1. Table A: ID integer, Kind integer,

(Kind=1 search Table B, Kind=2, search Table C)

  1. Table B: ID, name, price
  2. Table C: ID, item, amount

Table A

  • ID | Kind
  • 1 | 1
  • 2 | 1
  • 2 | 2
  • 3 | 2

TABLE B

  • ID name price
  • 1 name1 2.0
  • 2 name2 1.0

TABLE C

  • ID Item amount
  • 2 item2 1.0
  • 3 item3 1.0

what I am trying to search with one query and the result like:

- ID | Kind | name | price | item. | amount - 1 | 1 | name1 | 2.0 | ---- | ----- - 2 | 1 | name2 | 1.0 | ---- |. ----- - 2 | 2 | ---- | --- | item2 | 1.0 - 3 | 2 | ---- | --- | item3 | 1.0

Is it possible?

select A.ID,A.kind,B.name,B.price,C.item,C.amount from TableA 
case when Kind=1 Left Join TableB on A.ID=B.ID Then Left Join TableC on A.ID=C.ID order by ID

Just join with both tables, and make the Kind value part of the join condition. Use outer joins to get TableA rows even when no match is found for one join:

SELECT TableA.ID,
       TableA.Kind,
       TableB.name,
       TableB.price,
       TableC.item,
       TableC.amount
FROM TableA
LEFT JOIN TableB ON TableA.Kind = 1 AND TableA.ID = TableB.ID
LEFT JOIN TableC ON TableA.Kind = 2 AND TableA.ID = TableC.ID;

Alternatively, use normal joins in two separate queries, and combine them with lots of NULL columns:

SELECT TableA.ID,
       TableA.Kind,
       TableB.name,
       TableB.price,
       NULL AS item,
       NULL AS amout
FROM TableA
JOIN TableB USING (ID)
WHERE Table.Kind = 1

UNION ALL

SELECT TableA.ID,
       TableA.Kind,
       NULL,
       NULL,
       TableC.item,
       TableC.amount
FROM TableA
JOIN TableC USING (ID)
WHERE Table.Kind = 2;

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