指定MySQL加入

时间:2011-08-29 23:05:18

标签: php mysql sql join random

我有两个表,其中一个字段链接到另一个表中的ID,而在另一个表中,我需要检查一个值是否有效。表格如下所示:

TABLE1
id - table2_id- deleted - user_id

TABLE2
id - is_valid

现在,我尝试使用联接无济于事,但这正是我想要实现的目标:

从TABLE1中选择一行(ID),其中deleted = 0,user_id = $ id,然后我需要获取TABLE1的table2_id并进入具有table2_id ID的行的TABLE2并检查is_valid = 0

我还需要将结果限制为6并随机选择它们。 提前谢谢。

编辑:另一种可视化我想要实现的目标的方式:

$query = mysql_query("SELECT id, table2_id FROM table1 WHERE user_id = '$id' AND deleted = '0'");

        while ($row = mysql_fetch_array($query)) {   

            $table2_id = $row['table2_id'];
            $q = mysql_query("SELECT id FROM table2 WHERE id = '$table2_id' AND is_valid = '0'");

            if ($q) $final_ids[] = $row['id'];

        }

1 个答案:

答案 0 :(得分:3)

    SELECT table1.id -- add other fields you might want
      FROM table1
INNER JOIN table2 
        ON table1.table2_id = table2.id
     WHERE user_id = $user_id
       AND deleted = 0
       AND is_valid = 0 -- do you really mean 0 here?
  ORDER BY RAND()
     LIMIT 6