MySql查询代码从单个ID中获取唯一数据

时间:2018-12-13 17:51:59

标签: mysql database

如何列出订购了化学药品[NUMBER]的任何客户的客户名称和名称。

ORDERS

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

CUSTOMER

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

3 个答案:

答案 0 :(得分:3)

您可以将包含特定CUSTOMER订单的ORDERS<chemno>表与仅购买产品的储钱罐子查询结合在一起:

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

答案 1 :(得分:1)

我将在两个表之间使用一个join进行处理,然后按CUSTNUM表的列ORDERS分组,最后在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> )

答案 2 :(得分:1)

好的,慢点...

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;

此任务的其余部分留给读者练习