2012-06-22 66 views
1

我正在構建一個查詢來收集來自多個表的數據。我想從一張表中抓取所有item_ids,然後根據item_id從其他表中收集其他數據來構建結果。我可以發誓,這是可能的;但是,我似乎無法讓它工作。這裏是我想要做的一個例子:MySQL查詢/子查詢問題

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

當然這只是一個例子。實質上,我需要使用子查詢中主查詢的item_id。我可以發誓,我以前做過,但我不記得如何...

我試圖做的只是一個查詢,而不是任何額外的編程語言。我想最終將其設置爲存儲過程。感謝或有任何幫助。

UPDATE

看起來像一個聯接沒有工作......感謝所有幫助。

這裏是我的,以防萬一別人最終查詢運行到這樣的事情:

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); 
+2

不,使用聯接 – kalpaitch

+0

我沒有嘗試加入,因爲我想通了實際查詢正想對此太多了。我會給你一個鏡頭...... – W3BGUY

+1

你應該使用一個帶有QA的內部連接,因爲你希望它的某個字段在where子句中不爲空 - 謝謝你接受我的答案。 – Sebas

回答

1
SELECT a.item_id AS mainID, b.anotherField 
FROM theMainTable a 
    INNER JOIN anotherTABLE b ON a.item_id=b.item_id 

應避免使用select語句子查詢,因爲它們將針對主表中的每個返回行進行計算,而內部連接確保適當的優化和表格路徑。

1

您應該使用

SELECT mt.itemID AS mainID, at.anotherField 
FROM theMainTable mt INNER JOIN anotherTABLE at 
ON mt.itemID = at.item_id 
1
SELECT themaintable.item_id AS mainID, 
     anothertable.anotherfield 
FROM themaintable 
     INNER JOIN anothertable 
       ON item_id = mainid; 
1

嘗試這樣:

SELECT 
    item_id AS mainID, 
    anotherField 
FROM theMainTable 
INNER JOIN anotherTABLE ON item_id=mainID; 
1

加入兩個表,這就是爲什麼你有鑰匙:

SELECT table_x.id, table_y.another_field 
FROM table_x 
INNER JOIN table_y ON table_x.id = table2.x_id; 
1

如果你真的需要有一個嵌套查詢然後執行:

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

n ested查詢不起作用可能是因爲您沒有定義該字段來自的表,並且列名稱含糊不清。

說了上面,這真的是你會使用,而不是加入一個案例:

SELECT theMainTable.mainID, 
     anotherTABLE.anotherField 
FROM theMainTable INNER JOIN anotherTABLE 
ON theMainTable.item_id = anotherTABLE.mainID