简体   繁体   中英

Return column's values that has values from another table

I have below 2 sample tables:

Orders: 
+--------+----------+
| UserID | ProductID| 
+--------+----------+
|      1 |    1     | 
|      2 |    4     |
|      3 |    3     | 
|      4 |    3     | 
+--------+----------+

Products:
+----------+-------+
| ProductID| Price | 
+----------+-------+
|      1   | A     | 
|      2   | D     | 
|      3   | G     |
|      4   | J     |
+----------+-------+

I would like to return the ProductID of Products table that only has value (or has UserID ) in the Orders table.

So the results would be, the below column:

+----------+
| ProductID| 
+----------+
|      1   |  
|      3   | 
|      4   |
+----------+
SELECT ProductID FROM Products WHERE ProductID IN (SELECT ProductID from Orders)

How about just doing:

select distinct productId
from orders;

Presumably, the productid is correct in the table -- so you don't have to check if a match actually occurs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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