LEFT将子查询连接到表1到另一个查询到table1

时间:2017-05-19 08:43:31

标签: mysql subquery left-join

我想知道当两者都与同一个表相关时,我是否可以将子查询加入另一个查询。

此查询将为我提供客户已完成的第一次预订(QUERY1):

SELECT ID, AN_ID, BUS_ID, DONE_DATE, BV, SET_DATE, REG_DATE
FROM `TABLE_1`
RIGHT JOIN `TABLE_2`on (TABLE_1.AN_ID = TABLE2.BEN_ID)
WHERE ((((TABLE1.AN_ID > 0)) AND (TABLE1.STATUS = 3)) AND ( TABLE1.DONE_DATE > 0)) AND TABLE1.BEN_ID <> 41))
GROUP BY USER
ORDER BY TABLE1.DONE_DATE ASC

此查询应该为我提供客户已完成的第二次预订:

SELECT ID, AN_ID, BUS_ID, DONE_DATE, BV, SET_DATE, REG_DATE
FROM `TABLE_1`
RIGHT JOIN `TABLE_2`on (TABLE_1.AN_ID = TABLE2.BEN_ID)
**LEFT JOIN QUERY1**
WHERE ((((TABLE1.AN_ID > 0)) AND (TABLE1.STATUS = 3)) AND ( TABLE1.DONE_DATE > 0)) AND TABLE1.BEN_ID <> 41))
    GROUP BY USER
    ORDER BY TABLE1.DONE_DATE ASC

我该怎么做?根据我的理解,整体查询应该给我第二低,因此每个客户的第二次预订(即:第一次重新预订)。为什么?:通过'left join'加入QUERY1会导致我在整个查询中包含所有记录,但是QUERY1中的记录,还是?

我试过'WHERE NOT EXISTS'(显示没有数据)和'WHERE NOT IN'(错误大约1列)。

有什么想法吗?期待您的专业知识!

P.S。:我认为像这样VIRTUAL TABLE可能会有所帮助,但说实话,我的SQL技能不符合那里描述的任何内容。 :(

2 个答案:

答案 0 :(得分:0)

只是为了说明草莓的观点

DROP TABLE IF EXISTS T;
CREATE TABLE T (ID INT, DT DATE);
INSERT INTO T VALUES
(1,'2017-10-01'),(1,'2016-01-01'),
(2,'2017-01-02'),(2,'2017-01-01');

SELECT ID, DT
FROM T
GROUP BY ID
ORDER BY DT  ASC

+------+------------+
| ID   | DT         |
+------+------------+
|    2 | 2017-01-02 |
|    1 | 2017-10-01 |
+------+------------+
2 rows in set (0.00 sec)

在两种情况下都没有检测到最早的日期。如果你想找到最早的日期,你应该使用MIN

SELECT ID, min(DT) FirstBooking
FROM T
GROUP BY ID
ORDER BY id

+------+--------------+
| ID   | FirstBooking |
+------+--------------+
|    1 | 2016-01-01   |
|    2 | 2017-01-01   |
+------+--------------+
2 rows in set (0.00 sec)

如果您需要找到第一个和第二个,那么行号模拟可能就是您想要的。

select id,dt,rownumber 
from
(
SELECT ID, DT 
        ,if(id<>@p,@rn:=1,@rn:=@rn+1) Rownumber
        ,@p:=id
FROM T, (select @rn:=0,@p:=0) rn
ORDER BY id,dt
) s 
where rownumber in (1,2)

+------+------------+-----------+
| id   | dt         | rownumber |
+------+------------+-----------+
|    1 | 2016-01-01 |         1 |
|    1 | 2017-10-01 |         2 |
|    2 | 2017-01-01 |         1 |
|    2 | 2017-01-02 |         2 |
+------+------------+-----------+
4 rows in set (0.00 sec)

答案 1 :(得分:0)

这是我在最后实施的解决方案:

 SELECT ID, AN_ID, BUS_ID, DONE_DATE, BV, SET_DATE, REG_DATE
    FROM TABLE_1
    JOIN 
    (
    SELECT AN_ID, MIN(DONE_DATE)
    FROM TABLE_1
    WHERE AN_ID >0
    AND DONE_DATE >0
    AND BEN_ID !=41385
    GROUP BY AN_ID
    ) tt ON tt.DONE_DATE = TABLE1.DONE_DATE AND tt.AN_ID = TABLE1.AN_ID
    JOIN `TABLE_2`on (TABLE_1.AN_ID = TABLE2.BEN_ID)