我在MySQL数据库中有两个表。在表A(A1)的第一列数据中,我有整数值。在表B(B1和B2)的第一和第二列中,我也有整数值。我想创建一个查询,它将给出A1在B1 - B2范围内的值。这可能与MySQL查询有关吗?
以下是我想知道如何做的一个例子:
Table A Table B
------- ------- --------
123 12 24
451 450 455
199 202 210
0 499 567
23 5 40
我正在寻找的SQL查询将返回匹配的A1,B1和B2值:
451 450 455
23 12 24
23 5 40
答案 0 :(得分:2)
select * from a, b where a1 between b1 and b2
就像交叉联接一样简单。它至少相当于MySQL和Oracle的内部联接。
答案 1 :(得分:0)
SELECT
A.A1,
B.B1,
B.B2
FROM
A
INNER JOIN B ON
B.B1 <= A.A1 AND
B.B2 >= A.A1
答案 2 :(得分:0)
SELECT
A.VALUE,
B.VAL_MIN,
B.VAL_MAX
FROM
TAB A,
TAB B
WHERE
A.VALUE >= B.VAL_MIN AND A.VALUE <= B.VAL_MAX
试试这个。
答案 3 :(得分:0)
试试这个:
SELECT a.A1, b.B1, b.B2
FROM `Table A` a
INNER JOIN `Table B` b ON b.B1 < a.A1 AND b.B2 > a.A1
答案 4 :(得分:0)
以下是查询:
SELECT A.a1,B.b1,B.b2
FROM A,B
WHERE A.a1 >= B.b1
AND A.a1 <= B.b2;
以下是示例代码的加载:
use junk
DROP TABLE IF EXISTS A;
DROP TABLE IF EXISTS B;
CREATE TABLE A (a1 int);
CREATE TABLE B (b1 int,b2 int);
INSERT INTO A VALUES (123),(451),(199),(0),(23);
INSERT INTO B VALUES ( 12, 24),(450,455),(202,210),(499,567),( 5, 40);
SELECT * FROM A;
SELECT * FROM B;
SELECT A.a1,B.b1,B.b2
FROM A,B
WHERE A.a1 >= B.b1
AND A.a1 <= B.b2;
结果如下:
mysql> use junk
Database changed
mysql> DROP TABLE IF EXISTS A;
Query OK, 0 rows affected (0.03 sec)
mysql> DROP TABLE IF EXISTS B;
Query OK, 0 rows affected (0.03 sec)
mysql> CREATE TABLE A (a1 int);
Query OK, 0 rows affected (0.08 sec)
mysql> CREATE TABLE B (b1 int,b2 int);
Query OK, 0 rows affected (0.06 sec)
mysql> INSERT INTO A VALUES (123),(451),(199),(0),(23);
Query OK, 5 rows affected (0.05 sec)
Records: 5 Duplicates: 0 Warnings: 0
mysql> INSERT INTO B VALUES ( 12, 24),(450,455),(202,210),(499,567),( 5, 40);
Query OK, 5 rows affected (0.06 sec)
Records: 5 Duplicates: 0 Warnings: 0
mysql> SELECT * FROM A;
+------+
| a1 |
+------+
| 123 |
| 451 |
| 199 |
| 0 |
| 23 |
+------+
5 rows in set (0.00 sec)
mysql> SELECT * FROM B;
+------+------+
| b1 | b2 |
+------+------+
| 12 | 24 |
| 450 | 455 |
| 202 | 210 |
| 499 | 567 |
| 5 | 40 |
+------+------+
5 rows in set (0.00 sec)
mysql> SELECT A.a1,B.b1,B.b2
-> FROM A,B
-> WHERE A.a1 >= B.b1
-> AND A.a1 <= B.b2;
+------+------+------+
| a1 | b1 | b2 |
+------+------+------+
| 23 | 12 | 24 |
| 451 | 450 | 455 |
| 23 | 5 | 40 |
+------+------+------+
3 rows in set (0.00 sec)