我有5张桌子。我需要从一个表中选择4个最近的帖子,并在四个单独的变量中获取这些帖子的ID,以用于其他表中的查询:
SELECT user FROM table1 WHERE subcategory = "$input" ORDER BY id DESC LIMIT 4;
所以我有我需要的东西。现在,我如何将这四个用户标识结果分配给新变量,以便在同一页面的未来查询中使用。
我需要像这样存储它:
$user1 = "Sue";
$user2 = "Dave";
$user3 = "Alicia";
$user4 = "Tim";
所以我可以这样使用它:
SELECT * FROM table2 WHERE user = $user1;
SELECT * FROM table2 WHERE user = $user2;
SELECT * FROM table2 WHERE user = $user3;
SELECT * FROM table2 WHERE user = $user4;
不要混淆问题,但是:最终目标是拥有多行但只有四列,其中行中的所有数据都由USER排在第一行。重要的是要注意,因为每组行由对其下面的数据中包含的内容的描述分隔。这些只是直列,很容易。像这样:
Sue Dave Alicia Tim
Sue Profile Dave Profile Alicia Profile Tim Profile
>>Answers to questions about work:
Sue Income Dave Income Alicia Income Tim Income
Sue Years Dave Years Alicia Years Tim Years
>>Answers to questions about school:
Sue Degree Dave Degree Alicia Degree Tim Degree
Sue Schools Dave Schools Alicia Schools Tim Schools
>>Answers to questions about life:
Sue Born Dave Born Alicia Born Tim Born
Sue Parents Dave Parents Alicia Parents Tim Parents
如果我可以将id结果读入单独的变量,那么对于每个部分(问题)我可以做类似的事情:
SELECT * FROM income WHERE user = "Sue";
SELECT * FROM income WHERE user = "Dave";
SELECT * FROM income WHERE user = "Alicia";
SELECT * FROM income WHERE user = "Tim";
SELECT * FROM degree WHERE user = "Sue";
SELECT * FROM degree WHERE user = "Dave";
SELECT * FROM degree WHERE user = "Alicia";
SELECT * FROM degree WHERE user = "Tim";
答案 0 :(得分:0)
您最好使用JOINS然后运行多个查询。以下是代码......
SELECT t1.user, t2.* FROM table1 as t1 LEFT JOIN table2 as t2 ON t1.id = t2.user_id WHERE t1.subcategory = "$input" ORDER BY t1.id DESC LIMIT 4
我希望您可以按照 t1.id = t2.user_id
的步调更改两个表中的相同键答案 1 :(得分:0)
虽然你要求的东西可以这样实现:
$id=1;
${"user".$id}="Sue";
这样$ user1将具有“Sue”,这样就可以很容易地使用数组:
$id=1;
$user[$id]="Sue";
或者更好的是,尝试在查询中使用Join一次获取所有数据,然后根据需要重新格式化。
答案 2 :(得分:0)
如果您不想使用JOINS,那么在执行第一个查询后,您应该使用foreach循环......
$user=array(); // i would suggest you for making an array
foreach($result_array as $key->$value)
{
//here you will get the ids in $value['user']
// and then you can use them in your queries
// so no need to store them in different variables and remembering them.
Edited:
$user[$key] = $value['user'];
}