0

我有一张像这样“移动”的桌子

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

标签“自行车”

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

标签“汽车”

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

标签“船”

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

我想在单个查询中包含“move”的所有数据以及“move”中存在的每个表的数据,并带有特定的 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  | ... |
| .. | ... | ... | ...   | ....  | ...  | ....  | .... | ... |
--------------------------------------------------------------

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

SELECT * FROM move WHERE id>0 

然后是一个 foreach

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

但是工作很辛苦,因为桌子移动很长......

我尝试这样做,但(显然)不起作用......

SELECT M.*, T.* FROM move as M, M.tab as T WHERE M.id>0 AND M.idTab=T.id 
4

2 回答 2

1

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

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

我为表格类型添加了一个计算列,假设可能相同的id内容可能出现在多个车辆表中。

于 2017-05-22T07:24:43.490 回答
0
Select 'bike' vehicle,column1,.... from bike
Union
Select 'boat',column1,... from boat
Union...
于 2017-05-22T07:23:12.860 回答