我正在尝试从几个不同的表创建一个派生表,如果我执行单个内部联接,一切正常,但是当我添加更多联接时,我无法获得所需的结果。这是我现在得到的:
表结构:
第一张表:
+------------+------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+------------+------+-----+---------+-------+
| TAG_ID | int(11) | NO | PRI | NULL | |
| STATUS | int(11) | YES | | NULL | |
| ENABLE | int(11) | YES | | NULL | |
| TIME_STAMP | bigint(20) | YES | | NULL | |
| VALUE | float | YES | | NULL | |
+------------+------------+------+-----+---------+-------+
第二张表:
+--------------------+---------------------+------+-----+------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------------+---------------------+------+-----+------------+----------------+
| TAG_ID | int(11) | NO | PRI | NULL | auto_increment |
| TAG_DEV_ID | int(11) | NO | | NULL | |
| TAG_NAME | varchar(256) | NO | | NA | |
.....................
| TAG_TIME_STAMP | bigint(20) unsigned | NO | | 0 | |
+--------------------+---------------------+------+-----+------------+----------------+
这是我现在要做的——首先,我在将两个表加入一个大表后创建一个视图:
CREATE VIEW U1_TEMP_TEST AS (SELECT TAG_ID AS TID, VALUE FROM table_1);
CREATE VIEW U1_TEST AS (SELECT * FROM table_2 AS T2 INNER JOIN U1_TEMP_TEST AS T1 ON T2.TAG_ID = T1.TID);
现在我需要将表连接到自身,这样我就可以从不同列中的“值”中获取行,我这样做:
SELECT U1.TAG_DEV_ID, U1.TAG_ID, U1.VALUE, U2.VALUE
FROM U1_TEST AS U1
INNER JOIN ((SELECT * FROM U1_TEST
WHERE (TAG_ID = 1 OR TAG_ID = 12 OR TAG_ID = 21)) AS U2)
ON U1.TAG_DEV_ID = U2.TAG_DEV_ID
WHERE (U1.TAG_ID = 4 OR U1.TAG_ID = 20 OR U1.TAG_ID = 14)
GROUP BY U1.TAG_DEV_ID;
我得到了这样的好结果:
+------------+--------+--------+-------+
| TAG_DEV_ID | TAG_ID | VALUE | VALUE |
+------------+--------+--------+-------+
| 1 | 4 | -0.5 | 2.1 |
| 2 | 14 | -12.7 | 0.4 |
| 3 | 20 | -5.7 | 9.5 |
+------------+--------+--------+-------+
但是,如果我尝试再添加一个这样的连接:
SELECT U1.TAG_DEV_ID, U1.TAG_ID, U1.VALUE, U2.VALUE, U3.VALUE
FROM U1_TEST AS U1
INNER JOIN ((SELECT * FROM U1_TEST
WHERE (TAG_ID = 1 OR TAG_ID = 12 OR TAG_ID = 21)) AS U2)
ON U1.TAG_DEV_ID = U2.TAG_DEV_ID
INNER JOIN ((SELECT * FROM U1_TEST
WHERE (TAG_ID = 3 OR TAG_ID = 13 OR TAG_ID = 22)) AS U3)
ON U1.TAG_DEV_ID = U3.TAG_DEV_ID
WHERE U1.TAG_ID = 4 OR U1.TAG_ID = 14 OR U1.TAG_ID = 24
GROUP BY U1.TAG_DEV_ID;
返回的数据不是我所期望的,并非所有值都被选中。也许第二个内部连接有问题,我被这个问题困扰了几个小时,无法理解为什么单个连接查询工作正常而最后一个没有。
谢谢你的帮助 !
编辑结果数据:
+------------+--------+-------+-------+-------+
| TAG_DEV_ID | TAG_ID | VALUE | VALUE | VALUE |
+------------+--------+-------+-------+-------+
| 1 | 4 | -0.5 | 3 | 0 |
| 2 | 14 | -12.7 | 0.5 | 1.6 |
+------------+--------+-------+-------+-------+
我希望它是这样的:
+------------+--------+-------+-------+-------+
| TAG_DEV_ID | TAG_ID | VALUE | VALUE | VALUE |
+------------+--------+-------+-------+-------+
| 1 | 4 | -0.5 | 3 | 0 |
| 2 | 14 | -12.7 | 0.5 | 1.6 |
| 3 | 21 | x | x | x |
+------------+--------+-------+-------+-------+