MySQL-如何根据两个不同表之间的关系从表中选择所有结果?

时间:2018-08-26 20:51:43

标签: mysql

我有三个表:查询操作员 Operator_Region

tables

在表中输入的数据如下:

每个运算符可以具有一个或多个区域。我需要显示 INQUIRY 表的所有结果,其中 Region 字段等于登录用户的( Operator )Operator_Region.regionName领域。参见下图:

sql select result

我正在尝试如下:

SELECT region FROM `INQUIRY`
INNER JOIN `OPERATOR` on `INQUIRY`.`region` WHERE `INQUIRY`.`region` IN (

SELECT
    regionName
FROM
    `OperatorRegion`
INNER JOIN `Operator` ON `OperatorRegion`.`OperatorID` = operatorID
WHERE
    operatorRegion.operatorID = 2)

我需要查询仅返回与已登录运算符的区域(在本例中为Alisson)匹配的INQUIRY表行。操作员区域位于“ operator region_table”中。

但返回为空。这是我的SQLFiddle

1 个答案:

答案 0 :(得分:0)

请考虑以下内容:

DROP TABLE IF EXISTS inquiry;

CREATE TABLE inquiry
(inquiry_id SERIAL PRIMARY KEY
,region VARCHAR(12) 
);

INSERT INTO inquiry VALUES
(1,'Hawaii'),
(2,'Hawaii'),
(3,'Paris'),
(4,'New York');

DROP TABLE IF EXISTS operator;

CREATE TABLE operator 
(operator_id SERIAL PRIMARY KEY
,operator_name VARCHAR(12) NOT NULL UNIQUE
);

INSERT INTO operator VALUES
(101,'John'),
(102,'Alisson'),
(103,'Peter');

DROP TABLE IF EXISTS operator_region;

CREATE TABLE operator_region 
(operator_id INT NOT NULL
,region VARCHAR(12) NOT NULL
,PRIMARY KEY (operator_id,region)
);

INSERT INTO operator_region (operator_id,region) 
VALUES (102,'New York'),
       (102,'Los Angeles'),
       (102,'Hawaii'),
       (101,'New York'),
       (103,'Paris');


SELECT i.* 
  FROM inquiry i 
  JOIN operator_region ro 
    ON ro.region = i.region 
  JOIN operator o 
    ON o.operator_id = ro.operator_id 
 WHERE o.operator_name = 'Alisson';
+------------+----------+
| inquiry_id | region   |
+------------+----------+
|          1 | Hawaii   |
|          2 | Hawaii   |
|          4 | New York |
+------------+----------+