MySql 从 select 的多个表结果中获取数据

MySql get data from multiple tables results from a select

我有一个这样的table"move"

----------------------------------
| id | ... | ... |  tab  | idTab |
----------------------------------
| 1  | ... | ... | bike  |  14   |
| 2  | ... | ... | car   |  57   |
| 3  | ... | ... | car   |  23   |
| 4  | ... | ... | bike  |  43   |
| 5  | ... | ... | boat  |  20   |
| .. | ... | ... | ...   | ....  |
----------------------------------

选项卡"bike"

---------------------------------
| id | code | name  | matr | ... |
---------------------------------
| .. | ...  | ....  | .... | ... |
| 14 | AAA  | MARIO | 111  | ... |
| .. | ...  | ....  | .... | ... |
| 43 | A1C  | JOHN  | EEE  | ... |
| .. | ...  | ....  | .... | ... |
---------------------------------

选项卡"car"

---------------------------------
| id | code | name  | matr | ... |
---------------------------------
| .. | ...  | ....  | .... | ... |
| 23 | 123  | JACK  | WER  | ... |
| .. | ...  | ....  | .... | ... |
| 57 | 2A2  | FRANK | MSS  | ... |
| .. | ...  | ....  | .... | ... |
---------------------------------

选项卡"boat"

---------------------------------
| id | code | name  | matr | ... |
---------------------------------
| .. | ...  | ....  | .... | ... |
| 20 | UJN  | PETER | WSX  | ... |
| .. | ...  | ....  | .... | ... |
---------------------------------

我想在单个查询中获得 "move" 的所有数据以及 "move" 中存在的每个 table 具有特定 idTab 的数据。

结果会是这样

--------------------------------------------------------------
| id | ... | ... |  tab  | idTab | code | name  | matr | ... |
--------------------------------------------------------------
| 1  | ... | ... | bike  |  14   | AAA  | MARIO | 111  | ... |
| 2  | ... | ... | car   |  57   | 2A2  | FRANK | MSS  | ... |
| 3  | ... | ... | car   |  23   | 123  | JACK  | WER  | ... |
| 4  | ... | ... | bike  |  43   | A1C  | JOHN  | EEE  | ... |
| 5  | ... | ... | boat  |  20   | UJN  | PETER | WSX  | ... |
| .. | ... | ... | ...   | ....  | ...  | ....  | .... | ... |
--------------------------------------------------------------

我不知道我是否有特定的 table 在移动中。 我可以这样查询

SELECT * FROM move WHERE id>0 

然后是

的 foreach
SELECT * FROM move["tab"] WHERE id=move["idTab"]

但是非常辛苦,因为 table 移动很长...

我试过这个但(显然)不起作用...

SELECT M.*, T.* FROM move as M, M.tab as T WHERE M.id>0 AND M.idTab=T.id 
Select 'bike' vehicle,column1,.... from bike
Union
Select 'boat',column1,... from boat
Union...

您的数据库设计不理想,我认为您不应该为每种类型的车辆设置单独的 table。话虽这么说,如果您使用 UNION 将三个 table 合并为一个,那么单个连接就可以产生您想要的结果。

SELECT t1.*, t2.*
FROM move t1
INNER JOIN
(
    SELECT id, code, name, matr, 'bike' AS tab
    FROM bike
    UNION ALL
    SELECT id, code, name, matr, 'car'
    FROM car
    SELECT id, code, name, matr, 'boat'
    FROM boat
) t2
    ON t1.idTab = t2.id AND
       t1.tab   = t2.tab

我为 table 的类型添加了一个计算列,假设相同的 id 可能出现在不止一辆车辆 table 中。