通过使用sql中第一个表中的数据从第二个表中获取数据

时间:2018-04-13 09:09:31

标签: mysql sql oracle

有两个表

表1 - CUSTOMERS

+----+----------+-----+-----------+----------+
| ID | NAME     | AGE | ADDRESS   | SALARY   |
+----+----------+-----+-----------+----------+
|  1 | Ramesh   |  32 | Ahmedabad |  2000.00 |
|  2 | Khilan   |  25 | Delhi     |  1500.00 |
|  3 | kaushik  |  32 | Kota      |  2000.00 |
|  4 | Chaitali |  25 | Mumbai    |  6500.00 |
|  5 | Hardik   |  25 | Bhopal    |  8500.00 |
|  6 | Komal    |  22 | MP        |  4500.00 |
|  7 | Muffy    |  27 | Indore    | 10000.00 |
+----+----------+-----+-----------+----------+

表2 - ORDERS

+-----+---------------------+------
|OID  | Age| CUSTOMER_ID | AMOUNT |
+-----+---------------------+------
| 102 | 22 |           3 |   3000 |
| 100 | 32 |           3 |   1500 |
| 101 | 25 |           2 |   1560 |
| 103 | 27 |           4 |   2060 |
+-----+---------------------+------

查询应该打印第一个表格中的所有数据,而不是AGE它应该打印OID

例如:

输入ID:3

输出:

ID  NAME     OID  ADDRESS   SALARY 
3  kaushik   100  Kota       2000.00

7 个答案:

答案 0 :(得分:0)

尝试

select c.ID, c.NAME, o.OID, c.ADDRESS, c.SALARY
from CUSTOMERS c, ORDERS o
where c.ID = o.CUSTOMER_ID 
AND c.AGE = o.Age

答案 1 :(得分:0)

这样的东西?

SELECT cust.id,
       cust.name,
       ordr.oid,
       cust.address,
       cust.salary
FROM   customers cust
JOIN   orders    ordr
  ON   cust.id = ordr.customer_id
 AND   cust.age = ordr.age;

答案 2 :(得分:0)

您需要加入主键和Age col,因为有多条记录。

SELECT
    c.ID, 
    c.NAME, 
    o.OID, 
    c.ADDRESS, 
    c.SALARY
    from CUSTOMERS c
    JOIN ORDERS o ON c.ID = o.CUSTOMER_ID 
    AND c.AGE = o.Age

答案 3 :(得分:0)

使用LEFT JOIN尝试此操作,

SELECT c.id,c.name,o.oid,c.address,c.salary
FROM customers as c 
LEFT JOIN ORDERS as o ON o.customer_id=c.id AND o.age=c.age

答案 4 :(得分:0)

试试这个。

Select  Customers.Id, 
    Customers.Name, 
    Orders.Oid, 
    Customers.Address, 
    Customers.Salary
From Customers
Join Orders  On 
    Customers.Id = Orders.Customer_Id And 
    Customers.Age = Orders.Age

答案 5 :(得分:0)

试试这个

form_with[:customer, current_user], as: :profile do

答案 6 :(得分:-1)

使用外键ORDER表“CUSTOMER_ID”加入Customer表“ID”的主键

select C.ID, C.NAME, O.OID, C.ADDRESS, C.SALARY
from CUSTOMER C,
     ORDERS O
where C.ID = O.CUSTOMER_ID