基于多个条件在两个表之间连接

时间:2017-09-11 20:58:16

标签: mysql sql join

我的表格ip_from包含ip_tostart_timeend_timebytesall_audit列。 还有第二个名为project的表,其中包含iptimeproject列。 我需要加入表格,以便得到包含timebytestime列的结果表格。 需要考虑的事项是start_time仅匹配介于end_timeip之间的记录。 ip_from可以匹配ip_to+----------------+---------------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +----------------+---------------------+------+-----+---------+-------+ | ip_from | char(15) | NO | PRI | NULL | | | ip_to | char(15) | NO | PRI | NULL | | | bytes | bigint(20) unsigned | NO | | NULL | | | start_time | datetime | NO | PRI | NULL | | | end_time | datetime | YES | | NULL | | +----------------+---------------------+------+-----+---------+-------+

这两个表的架构是:

账户

+-----------+------------------+------+-----+---------+----------------+
| Field     | Type             | Null | Key | Default | Extra          |
+-----------+------------------+------+-----+---------+----------------+
| id        | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| project   | varchar(255)     | YES  |     | NULL    |                |
| ip        | varchar(32)      | YES  | MUL | NULL    |                |
| time      | timestamp        | YES  |     | NULL    |                |
+-----------+------------------+------+-----+---------+----------------+

all_audit

+-----------+------------------+------+-----+---------+----------------+
| Field     | Type             | Null | Key | Default | Extra          |
+-----------+------------------+------+-----+---------+----------------+
| project   | varchar(255)     | YES  |     | NULL    |                |
| time      | timestamp        | YES  |     | NULL    |                |
| bytes     | bigint(20) unsigned| NO   |     | NULL    |       |
+-----------+------------------+------+-----+---------+----------------+

结果

{{1}}

我知道这将是一个加入,但我不知道从哪里开始。指针将非常有用,因为我在sql语句中不是那么称职但愿意学习。

1 个答案:

答案 0 :(得分:1)

我怀疑你正在寻找这样的东西:

SELECT aa.project
     , aa.time
     , a.bytes
  FROM all_audit aa
  JOIN accounts a 
    on (aa.ip = a.ip_from OR aa.ip = a.ip_to) 
   AND aa.time BETWEEN a.start_time AND a.end_time