mysql查询代码,用于从单个id获取唯一的数据

c86crjj0  于 2021-06-17  发布在  Mysql
关注(0)|答案(3)|浏览(410)

如何列出只订购了化学品[编号]的客户的客户和姓名。 ORDERS table

+---------+--------+------------+------+
| CUSTNUM | CHEMNO | DATE       | QTY  |
+---------+--------+------------+------+
|  123456 |   1234 | 2000-00-00 |   35 |
+---------+--------+------------+------+
``` `CUSTOMER` table

+---------+-----------+-----------+
| CUSTNUM | NAME | LOCATION |
+---------+-----------+-----------+
| 123456 | AmChem | New York |
+---------+-----------+-----------+

tyu7yeag

tyu7yeag1#

你可以加入 CUSTOMER 以及 ORDERS 包含特定订单的表 <chemno> 使用只购买产品的custnum的子查询:

SELECT
    CUSTNUM, NAME 
FROM
    CUSTOMER c
INNER JOIN
    ORDERS o ON o.CUSTNUM = c.CUSTNUM and o.CHEMNO = <chemno>
INNER JOIN
    ( SELECT
          CUSTNUM 
      FROM
          ORDERS
      GROUP BY
          CUSTNUM 
      HAVING
          COUNT(DISTINCT CHEMNO) = 1 ) t ON t.CUSTNUM = o.CUSTNUM
4zcjmb1e

4zcjmb1e2#

我会用一个来解决这个问题 join 在两个表之间,然后按列分组 CUSTNUMORDERS 最后在 HAVING 子句,如下所示:

SELECT
    o.CUSTNUM,
    c.NAME
FROM
    ORDERS AS o
INNER JOIN
    CUSTOMER AS c ON c.CUSTNUM = o.CUSTNUM
GROUP BY
    o.CUSTNUM
HAVING
    ( COUNT(DISTINCT o.CHEMNO) = 1 AND MIN(o.CHEMNO) = <some_chemno> )
dgenwo3n

dgenwo3n3#

好吧,慢一天。。。

SELECT DISTINCT x.custnum 
  FROM orders x 
  LEFT 
  JOIN orders y 
    ON y.custnum = x.custnum 
   AND y.chemno <> x.chemno 
 WHERE x.chemno = 9377 
   AND y.order_id IS NULL;

这个任务的其余部分留给读者作为练习

相关问题