我有2张桌子:来自今天的订单&记录
Opened
我试图根据今天表中订单的ORDER ID的前三位数从Records表中获取完整记录。 我想要的结果是:
Table Name : Orders from today
+-----------+-----------+
|Order ID | Online |
+-----------+-----------+
| 550 | Yes |
| 551 | No |
| 552 | Yes |
| 553 | Yes |
+-----------+-----------+
Table Name : Records
+----------------+
| A |
+----------------+
| 548xxxxx |
| 549xxxxx |
| 550xxxxx |
| 551xxxxx |
| 552xxxxx |
| 553xxxxx |
| 554xxxxx |
+----------------+
XXXXX represents random number
我尝试过使用:Table Name : Records
+----------------+
| A |
+----------------+
| 550xxxxx |
| 551xxxxx |
| 552xxxxx |
| 553xxxxx |
+----------------+
但我只会遇到语法错误。我知道我可以使用%,但我不知道如何适应代码。
请帮忙,非常感谢!
EDIT! 假设今天订单的订单ID不是全部55%
谢谢!
答案 0 :(得分:0)
SELECT *
FROM orders
WHERE orderid IN ( SELECT (LEFT(orderid, 3)
FROM sample
WHERE orderid LIKE '55%'));
答案 1 :(得分:0)
可能的数据类型转换问题
尝试:
select *
from orders o1
left join records r2
on cast(o1.orderid as varchar(3)) = left(r2.orderid,3)
答案 2 :(得分:0)
我想我得到了你想要的东西。如果您需要帮助,请告诉我。 SQLFiddle 链接。 的代码:强>
CREATE TABLE IF NOT EXISTS ordersFromToday (
order_ID INT,
online VARCHAR(4),
PRIMARY KEY (order_ID)
);
INSERT INTO ordersFromToday (order_ID,online) VALUES(550,'yes'),(551,'no'),(552,'yes'),(553,'yes');
CREATE TABLE IF NOT EXISTS records (
record_ID INT,
PRIMARY KEY (record_ID)
);
INSERT INTO records (record_ID) VALUES (5481213),(5494833),(5505983),(5519080),(5524984),(5531315),(5549858);
CREATE PROCEDURE GetAllProducts()
BEGIN
# Declare needed variables
DECLARE finished BOOLEAN DEFAULT FALSE;
DECLARE orderIDHold INT;
# cursor for each order_ID
DECLARE orderNumber CURSOR FOR
( SELECT order_ID FROM ordersFromToday);
# our continue handler for quitting the loop
DECLARE CONTINUE HANDLER
FOR NOT FOUND SET finished = TRUE;
# create a table to store these values
DROP TABLE IF EXISTS tempReportTbl;
CREATE TABLE IF NOT EXISTS tempReportTbl (
order_ID INT,
PRIMARY KEY (order_ID)
);
# open cursors
OPEN orderNumber;
# start loop
mainFunc: loop
FETCH orderNumber INTO orderIDHold;
IF finished = TRUE THEN
LEAVE MAINFUNC;
END IF;
SET @searchOrderID :=orderIDHold;
INSERT INTO tempReportTbl (order_ID)
SELECT * FROM records r1 where r1.record_ID LIKE concat(@searchOrderID,'%');
# end loop
END LOOP mainFunc;
# close cursors
CLOSE orderNumber;
END //
<强>输出:强>
ORDER_ID