以下是表格
表1
price col1 col2 time
10 1 1 10
100 1 1 13
150 1 1 15
表2
id startTm endTm col1 col2
1 12 20 1 1
2 15 26 1 1
3 11 13 1 1
我希望表2中的所有行都满足startTm> = x和endTm< = y。对于结果中的每一行,我想查找表1中所有记录的计数,其中table1.time位于startTm,endTm位于该特定行
像这样 -
SELECT (@sTime:=T2.startTm) AS startTm,JT.totalNo, JT.totalPrice,
(@eTime:=T2.endTm) AS endTm
some more columns FROM table 2 AS T2
LEFT JOIN (SELECT COUNT(id) AS totalNo,col1, col2 SUM(price) AS
totalPrice FROM table 1 WHERE time BETWEEN @sTime AND @eTime GROUP
BY col1, col2)
AS JT ON JT.col1 = T2.col1
WHERE T2.startTm >= some value AND T2.endTm <= some value.
没有相关的外键。我没有得到正确的结果。怎么做?
修改
我希望表2中的所有记录都在指定的时间范围内,假设startTm&gt; = 10到endTm&lt; = 20 所以输出表将是
startTm endTm totalNo totalPrice some more col
12 20 2 250 ...
11 13 1 100 ...
计算总价格和总数我想要考虑该特定行的startTm和endTime。
答案 0 :(得分:1)
这是你想要的吗?
SELECT startTm, endTm, COUNT(price), SUM(price), t3_others, t1_others
FROM
(
SELECT T3.startTm AS startTm, T3.endTm AS endTm, T3.others AS t3_others, T1.price AS price, T1.others AS t1_others
FROM T1
RIGHT JOIN
(
SELECT T2.startTm, T2.endTm, T2.others
FROM T2
WHERE T2.startTm >= 10 AND T2.endTm <= 20 AND T2.col1 = col1_value AND T2.col2 = col2_value
) AS T3
ON T1.time >= T3.startTm AND T1.time <= T3.endTm
) AS T4
GROUP BY startTm, endTm;
根据需要添加其他字段。
答案 1 :(得分:0)
尝试以下查询:
从表1中选择t1。*,t2。*为t1 RIGHT JOIN表2为t2 ON t1.col1 = t2.col1 WHERE t2.startTm&gt; ='你的值'和t2.endTm&lt; ='你的值'