我的问题
我试图根据参数从多个表中选择一行,但我对 SQL 连接的有限知识阻碍了我。有人能指出我正确的方向吗?
考虑这些表结构:
+-----------------------+ +---------------------+
| Customers | | Sellers |
+-------------+---------+ +-----------+---------+
| Customer_ID | Warning | | Seller_ID | Warning |
+-------------+---------+ +-----------+---------+
| 00001 | Test 1 | | 00008 | Testing |
| 00002 | Test 2 | | 00010 | Testing |
+-------------+---------+ +-----------+---------+
我想要做的是一个 SELECT
来仅检索一行,并且在这一行中将是基于 X_ID 字段的每个表的“警告”字段。
期望的结果
因此,如果我提交以下信息,我将收到以下结果:
示例1:
Customer_ID = 00001
Seller_ID = 00008
Results:
+-----------------------------------+
| Customer_Warning | Seller_Warning |
+------------------+----------------+
| Test 1 | Testing |
+------------------+----------------+
示例2:
Customer_ID = 00001
Seller_ID = 00200
Results:
+-----------------------------------+
| Customer_Warning | Seller_Warning |
+------------------+----------------+
| Test 1 | NULL |
+------------------+----------------+
我尝试过的
这是我当前的代码(我收到大量行):
SELECT c.Warning 'Customer_Warning', s.Warning AS 'Seller_Warning'
FROM Customers c,Sellers s
WHERE c.Customer_ID = @Customer_ID
OR s.Seller_ID = @Seller_ID
但我也尝试过 UNION
、UNION ALL
和 JOIN
。我应该采用哪种方法?
最佳答案
由于您并未真正将表连接在一起,只是从每个表中选择一行,因此您可以这样做:
SELECT
(SELECT Warning
FROM Customers
WHERE Customer_ID = @Customer_ID) AS Customer_Warning,
(SELECT Warning
FROM Sellers
WHERE Seller_ID = @Seller_ID) AS Seller_Warning
关于sql - UNION 或 JOIN 用于从多个表中进行 SELECT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26932456/