[英]combine two different queries into one
我有以下查询:
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
clothes和city=Australia
的行,但是当我使用Union时它会返回所有行。 我不知道如何让它发挥作用。 如果有人可以帮助我会很感激。
你不需要联盟。 只需加入所有表,并在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,并使用它们在查询中加入它们,但这是另一个故事。
您只需要 :
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
。
如果你想要两者,那么你可以使用aggregation和having子句:
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(*)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.