想要结合两个SQL查询以获得常见结果

时间:2014-09-29 14:11:36

标签: php mysql sql

如果以下两个条件都适用于该特定location_id,则想要从location_context表中获取location_id

    SELECT location_id 
    FROM location_context 
    WHERE relation_type = '2' 
    AND relation_table = 'locations' 
    AND relation_table_id = '$_GET[cat]' 
    AND is_active = '1'

    SELECT location_id 
    FROM location_context 
    WHERE relation_type = '1' 
    AND relation_table = 'locations' 
    AND relation_table_id = '$_GET[pro]' 
    AND is_active = '1'

3 个答案:

答案 0 :(得分:2)

以下是您正在寻找的查询:

SELECT L.location_id
FROM location_context L
WHERE L.relation_table = 'locations'
    AND L.is_active = '1'
    AND ((L.relation_type = '2' AND L.relation_table_id = '$_GET[cat]')
        OR (L.relation_type = '1' AND L.relation_table_id = '$_GET[pro]'))

希望这会对你有所帮助

答案 1 :(得分:1)

使用JOIN的查询:

SELECT c1.location_id 
 FROM location_context c1
 JOIN location_context c2 ON c2.location_id = c1.location_id
 -- first query conditions
 WHERE c1.relation_type = '2' 
 AND c1.relation_table = 'locations' 
 AND c1.relation_table_id = '$_GET[cat]' 
 AND c1.is_active = '1'
 -- second query conditions
 AND c2.relation_type = '1' 
 AND c2.relation_table = 'locations' 
 AND c2.relation_table_id = '$_GET[pro]' 
 AND c2.is_active = '1'

答案 2 :(得分:0)

使用MySQL的IN()函数尝试这样的事情:

SELECT location_id 
FROM location_context 
WHERE relation_type IN('1', '2') 
AND relation_table = 'locations' 
AND relation_table_id IN ($_GET['pro'], $_GET['cat']) 
AND is_active = '1'