简体   繁体   中英

Select the same column with two different foreign keys from another table

I feel like I am close to my solution, but not quite there. I am trying to select testRun.build twice,

First time based on the current run ( Results.build_fk ) and based on the last run where the test passed ( Results.lastPass ).

This is the Select statement I have so far, which I feel like should work ( because of this answer ), but it is telling me "Subquery returns more than 1 row".

SELECT Results.build_fk, Results.testCaseID, Results.pass, Results.time, 

( SELECT testRun.build

  FROM testRun 

 INNER JOIN Results r1 ON r1.build_fk = testRun.runID 

) AS Last_build, 

( SELECT testRun.build

  FROM testRun 

  INNER JOIN Results r2 ON r2.lastPass = testRun.runID
) 
  AS Current_Build

 FROM Results 

  INNER JOIN testCases AS t1 ON t1.testCaseID = Results.testCaseID

  ORDER BY build_fk DESC, testCaseID ASC;

And here are sample tables, with sample data:

Results
(`build_fk`, `testCaseID`, `pass`, `time`, `lastPass`)
(1132, 200, 0, {some timestamp}, 1132)
(1133, 200, 0, {some timestamp}, 1132)
(1134, 200, 1, {some timestamp}, 1134)
(1132, 210, 0, {some timestamp}, 1132)
(1133, 210, 0, {some timestamp}, 1132)
(1134, 210, 1, {some timestamp}, 1134)

testRun
(`runID`, `build`)
(1132, 'build-1.0')
(1133, 'build-1.1')
(1134, 'build-1.2')

Sorry theres no SQLFiddle, I couldn't get it to create the tables properly.

I think the additional joins in the subqueries are unnecessary:

SELECT r.build_fk, r.testCaseID, r.pass, r.time, 
       (SELECT tr.build
        FROM testRun tr
        WHERE r.build_fk = tr.runID 
       ) AS Last_build, 
       (SELECT tr.build
        FROM testRun tr
        WHERE r.lastPass = tr.runID
       ) AS Current_Build
FROM Results  r INNER JOIN
     testCases t1
     ON t1.testCaseID = r.testCaseID
ORDER BY build_fk DESC, testCaseID ASC;

You want the subquery to refer to the outer query (in this version using the r table alias). This is called a correlated subquery.

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