1

我正在构建一个查询以从多个表中收集数据。我想item_ids从一个表中获取所有数据,然后通过从其他表中收集其他数据来构建结果item_id。我可以发誓这是可能的。但是,我似乎无法让它工作。这是我正在尝试做的一个例子:

SELECT item_id AS mainID, 
 (SELECT anotherField 
  FROM anotherTABLE 
  WHERE item_id=mainID) 
FROM theMainTable;

当然,这只是一个例子。本质上,我需要在子查询中使用item_id来自主查询的。我本可以发誓我以前做过这个,但我不记得是怎么...

我试图通过一个查询来做到这一点,而不是使用任何额外的编程语言。我想最终将其设置为存储过程。感谢或对此有任何帮助。

更新

看起来加入确实有效...感谢您的所有帮助。

这是我的最后一个查询,以防万一其他人遇到这样的事情:

SELECT DISTINCT
    Q.item_id, Q.timestamp, Q.employee,
    QA.employeeNotes, Q2.itemDesc, Q2.itemExtraData
FROM 
    itemLog Q 
LEFT JOIN 
    itemComments QA ON Q.item_id = QA.item_id 
LEFT JOIN 
    itemLog Q2 ON Q.item_id = Q2.item_id AND Q2.type = 'begin' 
WHERE 
    Q.verb = 'itemStatus' 
    AND NOT (QA.employeeNotes IS NULL);
4

6 回答 6

1

你应该使用

SELECT mt.itemID AS mainID, at.anotherField
FROM theMainTable mt INNER JOIN anotherTABLE at
ON mt.itemID = at.item_id
于 2012-06-22T14:32:59.687 回答
1
SELECT a.item_id AS mainID, b.anotherField 
FROM theMainTable a
    INNER JOIN anotherTABLE b ON a.item_id=b.item_id

您应该避免在 select 语句中使用子查询,因为它们将针对从主表返回的每个行计算,而内部连接确保正确的优化和表路径。

于 2012-06-22T14:33:21.960 回答
1
SELECT themaintable.item_id AS mainID, 
       anothertable.anotherfield 
FROM   themaintable 
       INNER JOIN anothertable 
               ON item_id = mainid; 
于 2012-06-22T14:33:41.330 回答
1

尝试这样的事情:

SELECT
    item_id AS mainID,
    anotherField
FROM theMainTable
INNER JOIN anotherTABLE ON item_id=mainID;
于 2012-06-22T14:33:45.617 回答
1

加入这两个表,这就是为什么你有键:

SELECT table_x.id, table_y.another_field
FROM table_x
INNER JOIN table_y ON table_x.id = table2.x_id;
于 2012-06-22T14:36:45.607 回答
1

如果您确实需要嵌套查询,请执行以下操作:

SELECT item_id AS mainID, 
   (SELECT anotherField 
    FROM anotherTABLE 
    WHERE anotherTABLE.item_id=theMainTable.item_id) AS anotherField
FROM theMainTable;

嵌套查询不起作用的原因可能是因为您没有定义该字段来自的表并且列名不明确。

如上所述,这确实是您将使用连接的情况:

SELECT theMainTable.mainID, 
       anotherTABLE.anotherField
FROM theMainTable INNER JOIN anotherTABLE
ON theMainTable.item_id = anotherTABLE.mainID
于 2012-06-22T14:43:47.977 回答