简体   繁体   English

是否可以在另一个SELECT语句中使用SELECT语句的结果?

[英]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. 否则它将是somevalue = [list of result rows] ,这没有任何意义。

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. 编辑:我刚刚注意到你正在使用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. 在MySQL中,这些子选择将创建没有索引的派生表。 Looking for OwnerID and BlockID in those derived tables will do a full table scan of them. 在这些派生表中查找OwnerID和BlockID将对它们进行全表扫描。 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. 如果$ UserCode和$ BlockUserCode将子选择的结果缩小到单行,这可能无关紧要,但如果它们返回相当多的行,它将真正减慢您的查询速度。

Instead of using subqueries, you can just JOIN UserAccounts to get the rows you want. 您可以只使用JOIN UserAccounts来获取所需的行,而不是使用子查询。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM