嘿伙计们需要更多帮助
我有3张桌子USERS, PROFILEINTERESTS and INTERESTS
个人资料利益有两个链接用户和兴趣的外键,它们只是由ID完成。
到目前为止我有这个
$statement = "SELECT
InterestID
FROM
`ProfileInterests`
WHERE
userID = '$profile'";
现在我想要它,以便它从Interests中选择从该查询得到的结果。
所以说给出3个数字
1
3
4
我希望它搜索ID为=的Interests表中的那些......我只是不知道如何用PHP实际编写它...
请帮忙。
答案 0 :(得分:2)
如果您需要PROFILEINTERESTS表中的值,则为最佳选项。
SELECT DISTINCT i.*
FROM INTERESTS i
JOIN PROFILEINTERESTS pi ON pi.interests_id = i.interests_id
WHERE pi.userid = $profileid
SELECT i.*
FROM INTERESTS i
WHERE EXISTS (SELECT NULL
FROM PROFILEINTERESTS pi
WHERE pi.interests_id = i.interests_id
AND pi.userid = $profileid)
SELECT i.*
FROM INTERESTS i
WHERE i.interests_id IN (SELECT pi.interests_id
FROM PROFILEINTERESTS pi
WHERE pi.userid = $profileid)
答案 1 :(得分:1)
您走在正确的轨道上,假设您使用此PHP代码执行上述查询:
$statement = mysql_query("SELECT InterestID FROM `ProfileInterests`
WHERE userID = '$profile'");
然后,您可以使用PHP循环动态生成一个SQL语句,该语句将从第二个表中提取所需的ID。因此,例如,继续上面的代码:
$SQL = "";
while ($statementLoop = mysql_fetch_assoc($statement)) {
//Note the extra space on the end of the query
$SQL .= "`id` = '{$statementLoop['InterestID']}' OR ";
}
//Trim the " OR " off the end of the query
$SQL = rtrim($SQL, " OR ");
//Now run the dynamic SQL, using the query generated above
$query = mysql_query("SELECT * FROM `table2` WHERE {$SQL}")
我没有测试过代码,但是应该工作。因此,此代码将生成如下SQL:
SELECT * FROM `table2` WHERE `id` = '1' OR `id` = '3' OR `id` = '4'
希望有所帮助,
spryno724
答案 2 :(得分:0)
很可能你想加入表格
select
i.Name
from
ProfileInterests p
inner join
interests i
on
p.interestid = i.interestid
where
p.userid = 1