简体   繁体   中英

Sub-query referencing a field in parent query

I have been researching this for a fair while and I cant seem to find a solution.

In the following query, I need the sub-query to reference MachineIdent in the outer query. The field MachineIdent is not ambiguous (Only exists in the table CoilPass).

I think currently the subquery returns all of the MachineIdent results where I only need it to return one (The record currently being retrieved)

The error returned is "Subquery returns more than one row"

Am I right in thinking that a SELECT statement works kind of like a loop, retrieving one row of information at a time?

SELECT MachineIdent,
ROUND(EntryGauge * (SELECT DisplayScaleFactor FROM webreportparametersetup AS w WHERE w.MachineIdent = CoilPass.MachineIdent AND w.ItemName = 'EntryGauge')) AS EntryGauge
FROM Coil INNER JOIN CoilPass ON Coil.CoilIdent=CoilPass.CoilIdent INNER JOIN PassSection ON CoilPass.PassIdent=PassSection.PassIdent

No, SQL doesn't work like this. You could narrow down the subquery to return only one result, but you really want to just include your new criteria into the existing query, something like this:

SELECT 
    MachineIdent,
    EntryGauge, 
    w.DisplayScaleFactor, 
    ROUND(EntryGauge * w.DisplayFactor) AS ScaledEntryGauge
FROM Coil INNER JOIN CoilPass ON Coil.CoilIdent=CoilPass.CoilIdent 
INNER JOIN PassSection ON CoilPass.PassIdent=PassSection.PassIdent 
INNER JOIN webreportparametersetup w ON w.MachineIdent = CoilPass.MachineIdent 
WHERE w.ItemName = 'EntryGauge'

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