简体   繁体   English

Oracle 使用“SELECT”中另一个表的子查询进行查询

[英]Oracle query with subquery from another table in "SELECT"

I have a table1, and table2.我有一个表 1 和表 2。 There are sevaral rows in table2 for ID from table1.表 1 中的 ID 在表 2 中有几行。 Example: Table1 (ID, Name, Age):示例:表 1(ID、姓名、年龄):

543 | John | 15
321 | Doe  | 17.
SELECT SCORE 
FROM TABLE2 
WHERE ID = 543

(many rows as response). (许多行作为响应)。

I need a query with some columns from table1, as well as first row in column from table2.我需要一个包含来自 table1 的某些列以及来自 table2 的列中的第一行的查询。

Something like that:像这样的东西:

SELECT A.NAME NAME,
       A.AGE AGE,
       (SELECT SCORE
        FROM TABLE2 B
        WHERE A.ID = B.ID
        AND ROWNUM = 1) SCORE
FROM TABLE1 A,
     TABLE2 B
WHERE A.ID = B.ID

Just use a correlated subquery with no join:只需使用没有连接的相关子查询:

SELECT A.NAME,
       A.AGE,
       (SELECT B.SCORE
        FROM TABLE2 B
        WHERE A.ID = B.ID AND ROWNUM = 1
       ) as SCORE
FROM TABLE1 A;

Let me note that there is no such thing as "the first row in a table".请注意,没有“表格中的第一行”这样的东西。 Tables represent unordered sets.表代表无序集。 You need a column to specify the ordering.您需要一列来指定排序。 This returns a value from an arbitrary row.这从任意行返回一个值。 It is offered here because you use the same logic in the question.在这里提供它是因为您在问题中使用了相同的逻辑。

Limit rows using FETCH as shown here .使用FETCH限制行,如此处所示 Before getting result, you may want to order data to get, for example, latest value.在获得结果之前,您可能希望对数据进行排序以获取最新值等。

SELECT A.NAME,
       A.AGE,
       (SELECT SCORE
        FROM TABLE2 B
        WHERE A.ID = B.ID
        FETCH FIRST 1 ROWS ONLY
       ) as SCORE
FROM TABLE1 A;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 Oracle 中查询以使用子查询进行选择 - Query in Oracle to select with subquery Oracle SQL:从一个表中选择一个计数,使用另一个表中的子查询缩小选择范围 - Oracle SQL: select a count from one table, narrow the selection with subquery from another table 从一个表中选择,插入到另一个表中 oracle sql 查询 - select from one table, insert into another table oracle sql query 从多个表中选择,然后插入另一个表中的Oracle SQL查询 - Select from multiple tables, insert into another table Oracle SQL query 如何 select 表中的所有条目,其中子查询按第一个查询中的 id 计数另一个表中的条目 - How to select all entries in a table with a subquery counting entries in another table by id from the first query 如何 select Oracle 中另一个子查询的最大列的行 - How to select the row with the max column from another subquery in Oracle Oracle SQL:在没有子查询联接的情况下从另一个表中排除ID - Oracle SQL: Exclude IDs from another table without subquery join Select 从另一个表查询 - Select query from another table Oracle中子查询的参考表 - Reference table from subquery in Oracle 选择一个表与另一个表的否定以及oracle主表sql查询中的数据 - Select Negation of one table from another along with data in master table sql query for oracle
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM