Here are my case:
(Kind=1 search Table B, Kind=2, search Table C)
Table A
TABLE B
TABLE C
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.