我有这样的表
用户
id | name
1 | john
2 | alicia
3 | alex
follow_table
id | follow | follower
1 | john | alex
2 | alicia | alex
帖子
id | title | content | name
1 | title john | ....... | john
2 | title alicia | ....... | alicia
3 | title alex | ....... | alex
示例;
$id = 'alex';
$select_one = select * from follow_table where follower = '$id';
$query_one = mysqli_query($mysqli, $select_one) or die (mysqli_error($mysqli));
while ($follow = mysqli_fetch_array($query_one)) {
$follow = $follow['follow'];
$select_two = select * from posts where name = '$follow';
$query_two = mysqli_query($mysqli, $select_two) or die (mysqli_error($mysqli));
while ($posts = mysqli_fetch_array($query_two)) {
echo $posts['title'];
}
}
结果将是这样的:
id | title
1 | title john
2 | title alicia
上面的实际sql是正确的,但我只是想在$ follow中添加一个查询。
我的问题是,如何将 user.id 3(alex)纳入字段 $ follow ? 我想要这样的东西
id | title
1 | title john
2 | title alicia
3 | title alex
感谢您已经愿意提供的帮助
答案 0 :(得分:1)
将$select_one
替换为:
SELECT name
FROM user
JOIN follow_table ON (
follow_table.follower = user.name
OR follow_table.follow = user.name
)
WHERE follower = '$id';
这将检索每个用户,然后是alex,和 alex本身。
答案 1 :(得分:0)
您可以使用CONCAT()
或CONCAT_WS()
作为派生字段来连接两列的结果。
SELECT
CONCAT_WS(' ', title, name) as full_name
FROM
//...
答案 2 :(得分:0)
在这种情况下你必须使用别名,你必须实现你的选择查询,我已经尝试过这个并且效果很好,
<?php
$select_one = select * from follow_table where id = '$id';
$query_one = mysqli_query($mysqli, $select_one) or die (mysqli_error($mysqli));
while ($follow = mysqli_fetch_array($query_one)) {
$follow = $follow['follow'];
$select_two = select posts.name as posted_name,posts.* from posts where name = '$follow';
$query_two = mysqli_query($mysqli, $select_two) or die (mysqli_error($mysqli));
while ($posts = mysqli_fetch_array($query_two)) {
echo $posts['title'];
echo $posts['posted_name'];
}
}