PHP PDO在同一查询中查询两个表

时间:2014-02-22 00:10:17

标签: php mysql

我有这个查询

$sth = $db->prepare(
    'SELECT shout_id FROM shout_info'
    . ' WHERE shout_location = "3"'
    . ' AND (shout_sex = "0" OR shout_sex = ?)'
    . ' AND (shout_age = "0" OR shout_age = ?)'
    . ' AND shout_location_spec = ? AND user_id <> ?'
    . ' ORDER BY date_created DESC LIMIT 15'
);

        $sth->bindValue(1, $user_sex);
        $sth->bindValue(2, $sql_general_age);
        $sth->bindValue(3, $user_workplace);
        $sth->bindValue(4, $user_id);
        $sth->execute();
        $workplace_array = $sth->fetchAll(PDO::FETCH_ASSOC);

它很长,但我想知道我如何也可以从另一个表中的列进行检查,检查将是AND shout_approved = "1"但是shout_approved在表shout_status中,shout_status的主要ID是shout_id,只是就像在shout_info中一样,所以我不知道如何使用与原始查询中检查的相同的ID来检查此表。 对不起,我想尽可能清楚地解释一下。

如果您还有其他需要,请告诉我

2 个答案:

答案 0 :(得分:1)

您需要LEFT OUTER JOIN

SELECT
    s.shout_id
FROM
    shout_info s
        LEFT OUTER JOIN
            shout_status ss
        ON
            ss.shout_id = s.shout_id
WHERE
    s.shout_location = "3" AND
    (s.shout_sex = "0" OR s.shout_sex = ?) AND
    (s.shout_age = "0" OR s.shout_age = ?) AND
    s.shout_location_spec = ? AND
    s.user_id <> ? AND
    ss.shout_approved = "1"
ORDER BY
    s.date_created DESC
LIMIT
    15

答案 1 :(得分:0)

这应该有效:

SELECT 
shout_id 
FROM 
shout_info 
WHERE shout_location = "3" 
AND (shout_sex = "0" OR shout_sex = ?)
AND (shout_age = "0" OR shout_age = ?) 
AND shout_location_spec = ? AND user_id <> ?
ORDER BY date_created DESC LIMIT 15'
Join shout_approved  on shout_approved.shout_id = shout_id 
where shout_approved = "1"