[英]how to select column with null value and use the id of the column to select another column of another table
考慮表需求和訂單
CREATE TABLE `req` (
`req_id` bigint(20) NOT NULL,
`order_date` timestamp NULL DEFAULT NULL,
`status` varchar(20) COLLATE utf8_bin DEFAULT NULL,
`order_id` bigint(20) NOT NULL,`
PRIMARY KEY (`req_id`),
KEY `order_id` (`order_id`),
CONSTRAINT `req_ibfk_16` FOREIGN KEY (`order_id`) REFERENCES `order` (`order_id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
/*!40101 SET character_set_client = @saved_cs_client */;
CREATE TABLE `orders` (
`order_id` bigint(20) NOT NULL,
`acc_id` bigint(20) DEFAULT NULL,
`acc_name` varchar(256) COLLATE utf8_bin DEFAULT NULL,
PRIMARY KEY (`order_id`),
KEY `index_name` (`order_id`,`account_id`),
CONSTRAINT `order_ibfk_1`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
/*!40101 SET character_set_client = @saved_cs_client */;
“要選擇列oder_id,oder_date和status其中status為null req的值,並使用oder id選擇acc_id列和acc_name of orders表”?
並將它們聯合起來作為
status , oder_id , acc_id, acc_name
SELECT status,order_date,order_id FROM req WHERE status is null;
但我有如何使用id選擇另一個表列並聯合顯示它的問題
我用它來從一個表中選擇列
SELECT status,order_date,order_id FROM req WHERE status is null;
我期望下面提到的選擇列的輸出
status,oder_id,acc_id,acc_name
您需要使用它們具有的關系來加入這兩個表基於您的表,order_id是'orders'
主鍵,並且是'req'
的FK
使用此代碼:
SELECT
req.status , req.oder_id , orders.acc_id, orders.acc_name
FROM
req, orders
WHERE
req.order_id = orders.order_id
and
req.status is null;
這基本上連接了兩個表,你需要寫出字段來自哪個表。 這是代碼的長版本,但它是最容易理解的方法。
如果您有任何疑問,請與我聯系。
編輯:通過非逗號分隔連接添加另一種方法。 請改用完全聯接。
SELECT
req.status , req.oder_id , orders.acc_id, orders.acc_name
FROM
req
Full Join
orders
on
req.order_id = orders.order_id
WHERE
req.status is null;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.