简体   繁体   中英

Is it possible to use results from a SELECT statement within another SELECT statement?

Here is my code but im sure its not the correct way of doing this.

mysql_query("SELECT * FROM BlockUsers
WHERE OwnerID =
(SELECT ID FROM UserAccounts WHERE Code='$UserCode')
AND
BlockID =
(SELECT ID FROM UserAccounts WHERE Code='$BlockUserCode')
LIMIT 1", $DB)

Can someone help? thanks!

Yes, but when you're doing an equality test like that (=, <, >, etc...), the subquery has to return a single value. Otherwise it'd be somevalue = [list of result rows] , which makes no sense.

You'd want:

SELECT * FROM BlockUsers
WHERE OwnerID IN (SELECT ID FROM UserAccounts WHERE.....)
              ^^--- use 'in' instead of '=';
SELECT * FROM BlockUsers
WHERE OwnerID IN
(SELECT ID FROM UserAccounts WHERE Code='$UserCode')
AND
BlockID IN
(SELECT ID FROM UserAccounts WHERE Code='$BlockUserCode')
LIMIT 1

or

SELECT * FROM BlockUsers AS bu
INNER JOIN UserAccounts AS ua1 ON ua1.ID = bu.OwnerID
INNER JOIN UserAccounts AS ua2 ON ua2.ID = bu.BlockID
WHERE ua1.Code = '$UserCode' AND ua2.Code = '$BlockUserCode'
LIMIT 1

I think. I didn't test any of this, but I'm pretty sure it's close.

Edit: I just noticed you're using MySQL. You definitely want to do inner joins instead of sub selects. In MySQL those sub selects will create derived tables which have no indexes. Looking for OwnerID and BlockID in those derived tables will do a full table scan of them. This may not matter if $UserCode and $BlockUserCode will narrow the results of the sub selects down to a single row, but if they return quite a few rows it will really slow your query down.

Instead of using subqueries, you can just JOIN UserAccounts to get the rows you want.

SELECT BlockUsers.* FROM BlockUsers
JOIN UserAccounts as UA1 ON Code='$UserCode' AND OwnerID = UA1.ID
JOIN UserAccounts as UA2 ON Code='$BlockUserCode' AND BlockID = UA2.ID
LIMIT 1

是的你可以,子查询,你可以在这里找到官方的mysql参考: http//dev.mysql.com/doc/refman/5.0/en/subqueries.html从你的查询我觉得你很好去假设你的子查询只返回1个值,或者@Marc B点使用IN而不是等号。

Try to use

SELECT * FROM BlockUsers, UserAccounts
WHERE (OwnerID = ID and BlockID=ID and Code in ('$BlockUserCode', '$UserCode')
LIMIT 1

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