MySQL - 获取$ var = array的数据?

时间:2012-12-26 05:54:23

标签: php mysql select

我有两张桌子

subscribers

id    subscriber     subscribe_to
1       user1          user2
2       user2          user3
3       user1          user2
4       user3          user4
5       user1          user2
6       user1          user7
7       user5          user2
8       user8          user9
9       user1          user10

我的另一张桌子是这样的: main

id    by_user      post_name
1     user1        somename1
2     user2        somename2
3     user1        somename3
4     user3        somename4
5     user3        somename5
6     user1        somename6
7     user2        somename7
8     user3        somename8

我想使用php-mysql从表1中获取user1的所有订阅(例如)。然后从表2中提取公用名,但我不知道如何获取第二个表

$get_subscriptions = mysql_query("SELECT * FROM `subscribers` WHERE `subscriber` = 'user1'");
if(mysql_num_rows($get_subscriptions) == 1){
$fetch = mysql_fetch_assoc($get_subscriptions);
$subscriptions = $fetch['subscribe_to'];//this will return an array with all the subscribed to users by user1
} 

现在,我想获取第二个表并获取所有post_name(来自$ subscriptions)。我不知道如何编写查询。

$get_posts= mysql_query("SELECT * FROM `main` WHERE....");

2 个答案:

答案 0 :(得分:3)

试试这个:

SELECT post_name FROM main 
WHERE by_user = 'user1' OR by_user IN (SELECT subscribe_to FROM subscribers WHERE subscriber = 'user1')

答案 1 :(得分:0)

$get_posts = mysql_query("SELECT * FROM `main` WHERE by_user IN ('" . implode("', '", $subscriptions) . "')");