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

ddhy6vgd  于 2021-06-15  发布在  Mysql
关注(0)|答案(2)|浏览(415)

我有以下两种表格:

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

我想做的是 orderqty 大于 stockqty 我想显示一个信息,说股票是不够的,什么时候 orderqty 小于 stockqty 然后就完成了。
这里主要关注的是确定 orderqty 小于或大于 stockqty .

hmtdttj4

hmtdttj41#

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
gzszwxb4

gzszwxb42#

请看这把小提琴,如果有用请告诉我。
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;

相关问题