如何在MySQL中进行特定查询

时间:2017-02-04 14:43:09

标签: mysql

mysql> select * from  Orders;
+------+------+------+------------+------------+
| ONO  | CNO  | ENO  | RECEIVED   | SHIPPED    |
+------+------+------+------------+------------+
| 1020 | 1111 | 1000 | 1994-12-10 | 1994-12-12 |
| 1021 | 1111 | 1000 | 1995-01-12 | 1995-01-15 |
| 1022 | 2222 | 1001 | 1995-02-13 | 1995-02-20 |
| 1023 | 3333 | 1000 | 2003-02-15 | NULL       |
| 1024 | 4444 | 1000 | 2003-02-15 | 2003-02-16 |
| 1025 | 5555 | 1000 | 2003-02-15 | 2003-02-16 |
+------+------+------+------------+------------+

mysql> select * from Employees;
+------+--------+-------+------------+
| ENO  | ENAME  | ZIP   | HDATE      |
+------+--------+-------+------------+
| 1000 | Jones  | 67226 | 1995-12-12 |
| 1001 | Smith  | 60606 | 1992-01-01 |
| 1002 | Brown  | 50302 | 1994-09-01 |
| 1003 | Green  | 28411 | 2002-09-01 |
| 1004 | Purple | 28411 | 2003-01-01 |
+------+--------+-------+------------+

mysql> select * from Customers;
+------+---------+------------------+-------+--------------+
| CNO  | CNAME   | STREET           | ZIP   | PHONE        |
+------+---------+------------------+-------+--------------+
| 1111 | Charles | 123 Main St.     | 67226 | 316-636-5555 |
| 2222 | Bertram | 237 Ash Avenue   | 67226 | 316-689-5555 |
| 3333 | Barbara | 111 Inwood St.   | 60606 | 316-111-1234 |
| 4444 | Will    | 111 Kenwood St.  | 54444 | 416-111-1234 |
| 5555 | Bill    | 211 Marlwood St. | 28408 | 416-111-1235 |
| 6666 | Keely   | 211 Pinewood St. | 28411 | 416-111-1235 |
| 7777 | Maera   | 211 Marlwood St. | 28408 | 416-111-1235 |
+------+---------+------------------+-------+--------------+

我需要:获取cnameename对,以便客户知名 cname已通过名为ename的员工下了订单。

我确信这似乎很容易,但我无法想象 这个。我试过这个:

select distinct Customers.CNAME, Employees.ENAME
from   Customers, Employees
where  Customers.CNO in (
    select Customers.CNO
    from   Customers, Orders
    where  Customers.CNO = Orders.CNO
) and
where  Employees.ENO in (
    select Employees.ENO
    from   Orders, Employees
    where  Employees.ENO = Orders.ENO
);

在多个版本中,但我似乎无法让它工作。这是我第一次使用SQL,所以对我来说这是一个新手。我真的很感激任何帮助。

4 个答案:

答案 0 :(得分:0)

您可以使用带有一对连接的select distinc(左连接,如果可能是on条件不匹配或内连接,如果匹配)

select distinct c.cname, e.ename
from Customers as c
left join Orders as o as o on o.cno = c.cno
left join Employees on e.eno =  o.eno

select distinct c.cname, e.ename
from Customers as c
inner join Orders as o as o on o.cno = c.cno
inner join Employees on e.eno =  o.eno

答案 1 :(得分:0)

input

使用join语句可以更轻松地读取您尝试执行的SQL。这将订单表与CNO值和订单表上的客户联系在一起,其中包含ENO值的员工。然后选择两列进行显示。

答案 2 :(得分:0)

试试这个

import requests
resp = requests.get('your url')
if not resp.ok:
    print resp.status_code

 SELECT DISTINCT Customers.CNAME,Employees.ENAME FROM Customers 
 JOIN Orders ON Customers.CNO=Orders.CNO 
 JOIN Employees ON Employees.ENO=Orders.ENO;

答案 3 :(得分:0)

SELECT DISTINCT c.cname, e.ename
  FROM orders o
  JOIN employees e USING (eno)
  JOIN clients c USING (cno);