将两个不同的查询合并为一个

时间:2015-09-21 13:21:30

标签: php mysql

我有以下查询:

    SELECT DISTINCT id, title
    FROM      
    ((SELECT 
        DISTINCT offers.id AS id, offers.title AS title

    FROM offers

    INNER JOIN categories
    ON offers.category=categories.title

    WHERE categories.title="Fashion clothes"

    GROUP BY offers.id
    ORDER BY offers.id)
    UNION ALL
    (SELECT 
        DISTINCT offers.id AS id, offers.title AS title

    FROM offers

    INNER JOIN cities
    ON offers.city=cities.title

    WHERE cities.title="Australia"

    GROUP BY offers.id
    ORDER BY offers.id)) as subquery

我想从表中提取包含category=Fashion衣服和city=Australia的行,但是当我使用Union时,它会返回所有行。 我不知道如何让它发挥作用。如果有人可以帮助我会很感激。

3 个答案:

答案 0 :(得分:2)

你不需要工会。只需加入所有表,并在where where子句中包含两个条件:

SELECT 
DISTINCT offers.id AS id, offers.title AS title

FROM offers
INNER JOIN categories
ON offers.category=categories.title
INNER JOIN cities
ON offers.city=cities.title

WHERE categories.title="Fashion clothes" AND cities.title="Australia"
ORDER BY offers.id

正如RubahMalam所指出的那样,当您按标题加入表时,您甚至不需要连接,因此查询可以简化为:

SELECT 
DISTINCT offers.id AS id, offers.title AS title

FROM offers

WHERE offers.category="Fashion clothes" AND offers.city="Australia"
ORDER BY offers.id

但是,最好在所有表格中使用单独的唯一ID,并使用这些ID在您的查询中加入它们,但这是另一个故事。

答案 1 :(得分:1)

你只需要:

SELECT id,title
FROM offers
WHERE category = "Fashion clothes" OR city = "Australia"
GROUP BY id,title
ORDER BY offers.id

您甚至不需要INNER JOIN。正如patrickh003所说,如果id是唯一列,则甚至不需要GROUP BY

答案 2 :(得分:0)

如果你想要两者,那么你可以使用聚合和拥有子句:

SELECT o.id, o.title
FROM offers o
WHERE o.category = 'Fashion clothes' AND o.city = 'Australia'
GROUP BY o.id, o.title
HAVING COUNT(*) = 2
ORDER BY o.id;

如果您可以在offers表格中包含重复项,那么您需要COUNT(DISTINCT o.category)子句中的HAVING而不是COUNT(*)