从MYSQL中的2个表中查询

时间:2015-04-15 04:04:09

标签: php mysql phpmyadmin

我在MySQL中有两个表:

表1

Week    From         Until
1    2015-04-01    2015-04-07
2    2015-04-08    2015-04-14
3    2015-04-15    2015-04-21
4    2015-04-22    2015-04-28

表2

Input_Date        Code
2015-04-10        123
2015-04-22        456
2015-04-25        123
2015-04-26        123
  1. 我使用此查询根据当前日期选择当前周:

    SELECT Week FROM table_1 WHERE(NOW()BETWEEN FromUntil

  2. 我需要选择“代码”并从表2中计算,其中“Code”= 123,“Input_Date”对应当前的“Week”。

  3. *如果当前日期是2015-04-23,则“周”将是= 4

    结果将是:

    Week   Code  Count
     4     123     2
    

2 个答案:

答案 0 :(得分:3)

尝试 -

SELECT t1.Week, t2.Code, COUNT(*) 
FROM table_1 t1 
LEFT JOIN table_2 t2
ON t2.Input_Date BETWEEN t1.From AND t1.Until
WHERE (NOW() BETWEEN t1.From AND t1.Until) 
AND t2.Code = 123

http://sqlfiddle.com/#!9/3d2a6/16

答案 1 :(得分:0)

在没有LEFT JOIN的情况下执行相同操作的替代方法

SELECT a.week, b.code, count(a.week) 
FROM table_1 a, table_2 b
WHERE (b.input_date BETWEEN a.from AND a.until)
AND (NOW() BETWEEN a.From AND a.Until)
AND b.code = 123