简体   繁体   English

如何在sql查询中匹配两个不同的表?

[英]How to match two different tables in sql query?

I have these two kinds of table below:我有下面这两种表:

 Stocks Table          Order Table
-------------         -------------
| stockid   |         | orderid   |
| stockname |         | orderqty  |
| stockqty  |         | stockid   |
-------------         -------------

What I want to do is when orderqty is greater than stockqty I want to display a message saying that stocks are not enough, and when orderqty is less than stockqty then it is done.我想做的是当orderqty大于stockqty时我想显示一条消息说库存不够,当orderqty小于stockqty时就完成了。

The main concern here is to identify wether orderqty is less than or greater than stockqty .这里主要关注的是确定orderqty是小于还是大于stockqty

Please see this DB Fiddle and let me know if it helps.请查看此 DB Fiddle,如果有帮助请告诉我。

https://www.db-fiddle.com/f/hgEdnyeTTuxamXna9ELL3P/2 https://www.db-fiddle.com/f/hgEdnyeTTuxamXna9ELL3P/2

CREATE TABLE t_stock (
  stockid INT,
  stockname VARCHAR(50),
  stockqty BIGINT
);
INSERT INTO t_stock (stockid, stockname, stockqty) VALUES (1, 'salmon', 150);
INSERT INTO t_stock (stockid, stockname, stockqty) VALUES (2, 'asparagus', 275);
INSERT INTO t_stock (stockid, stockname, stockqty) VALUES (3, 'lemon', 300);


CREATE TABLE t_order (
  orderid INT,
  orderqty BIGINT,
  stockid INT
);
INSERT INTO t_order (orderid, orderqty, stockid) VALUES (13, 150, 3);
INSERT INTO t_order (orderid, orderqty, stockid) VALUES (14, 275, 2);
INSERT INTO t_order (orderid, orderqty, stockid) VALUES (15, 300, 1);


SELECT o.orderid
      ,o.stockid
      ,o.orderqty
      ,s.stockqty
      ,CONCAT(CASE WHEN o.orderqty > s.stockqty
                   THEN 'stocks are not enough for '
                   WHEN o.orderqty = s.stockqty
                   THEN 'stocks are just enough for '
                   ELSE 'we have plenty of stock for '
                   END, s.stockname) as stockqty_analysis
  FROM t_stock s INNER JOIN t_order o
    ON s.stockid = o.stockid;
SELECT o.orderid, 
       o.orderqty,
       s.stockqty,
       'stocks are not enough' AS message 
FROM orders o
JOIN stocks s ON o.stockid = s.stockid
WHERE o.orderqty < s.stockqty

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM