How do I (SELECT) populate two objects from two tables with a single query?

最后都变了- 提交于 2019-12-02 07:23:13

It seems this your latest query attempt:

SELECT a1.*, p.lifeSpan, a2.* 
FROM Zoo AS z 
INNER JOIN Plants AS p ON p.parent_id=z.id 
INNER JOIN Animal AS a1 ON (a1.id=z.predator)
INNER JOIN Animal AS a2 ON (a2.id=z.prey)";
WHERE z.preyType=@carnivore

Discard the semicolon from inside the statement. Also discard the double quote.

Just to simplify the SQL, exclude the WHERE clause for now.

Then you should be in a better position to address the issue of parentheses which Access' db engine requires for multiple joins.

SELECT a1.*, p.lifeSpan, a2.* 
FROM
    ((Zoo AS z 
    INNER JOIN Plants AS p ON p.parent_id=z.id) 
    INNER JOIN Animal AS a1 ON a1.id=z.predator)
    INNER JOIN Animal AS a2 ON a2.id=z.prey

Notice I discarded those parentheses which enclosed the ON expressions. Simple ON expressions don't require them. If you had a compound expression for ON, then you would need parentheses like this:

ON (p.parent_id=z.id AND p.foo = z.bar)

The sample query I suggested looks correct to me. (If it works for you, add your WHERE clause back again.) However, I don't pay close attention to parentheses placement because I use Access' query designer to set up joins ... and it adds the parentheses the db engine requires.

I urge you to do the same. If you're using an Access db from Dot.Net without having a copy of Access installed, you really should get a copy. Trying to use a database without that database's native development tools is an unreasonable challenge ... somewhat like trying to type while wearing mittens.

SELECT pred.col1 AS PredCol1, ..., pred.colx AS PredColx, 
       prey.col1 AS PreyCol1, ..., prey.colx AS PreyColx
    FROM Zoo z
        INNER JOIN Animal pred
            ON z.predator = pred.id
        INNER JOIN Animal prey
            ON z.prey = prey.id
    WHERE z.preyType = @carnivore

Alternatively, you might want something like this instead.

SELECT 'Predator' AS AnimalType, pred.*
    FROM Zoo z
        INNER JOIN Animal pred
            ON z.predator = pred.id
    WHERE z.preyType = @carnivore
UNION ALL
SELECT 'Prey' AS AnimalType, prey.*
    FROM Zoo z
        INNER JOIN Animal prey
            ON z.prey = prey.id
    WHERE z.preyType = @carnivore

Try with Joining the tables

SELECT aPrey.Name as PreyName, aPredatior.Name as PredatorName 
FROM Zoo AS z 
LEFT JOIN Animal AS aPrey On aPrey.id= z.prey
LEFT JOIN Animal AS aPredatior On aPredatior.id= z.predator
WHERE z.preyType=@carnivore
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!