我有两个表(Friends和News_Feed)。我需要从News_Feed表中检索最新的行(最高ID)。问题是我只想在News_Feed表中选择与Friends表中两列中任何一列相关的行。我还需要通过News_Feed.id订购,因此创建两个查询(例如首先选择我的朋友,然后循环到News_Feed查询)将无效。表格设置如下:
-Friends -
ID
用户
user_friending
News_Feed
ID
pertaining_user
行动
orig_comment
我当前的,不工作的查询是......
$result = mysql_query("SELECT * FROM News_Feed WHERE pertaining_user=(SELECT user FROM Friends WHERE user_friending='37' AND is_confirmed='1' UNION SELECT user_friending FROM Friends WHERE user='37' AND is_confirmed='1') AND orig_comment='0' ORDER BY id DESC")or die(mysql_error());
while($row_news = mysql_fetch_array($result)){
这返回子查询返回多行错误,我理解。必须有办法做到这一点。
答案 0 :(得分:0)
您可能正在寻找IN
关键字。
SELECT *
FROM News_Feed
WHERE pertaining_user IN
(
SELECT user
FROM Friends
WHERE user_friending='37'
AND is_confirmed='1'
UNION
SELECT user_friending
FROM Friends
WHERE user='37'
AND is_confirmed='1')
AND orig_comment='0'
ORDER BY id DESC
答案 1 :(得分:0)
使用exists
:
select
*
from
News_Feed f
where
exists (
select
1
from
friends u
where
(u.user = f.pertaining_user and u.user_friending = '37')
or (u.user_friending = f.pertaining_user and u.user = '37')
and u.is_confirmed = 1
)
order by
f.id desc
这比尝试使用in
union
要快得多。它会进行半连接并立即抛出无效行。