[英]SQL to return results if multiple matches in a pivot table
channel_data table
-------------
entry_id
content
channel_title table
-------------
entry_id
title
category_posts table
-------------
entry_id
category_id
sample data for category_posts category_posts的示例数据
entry_id cat_id
2 10
2 11
2 30
2 40
3 10
3 11
I need to be able to query the data so I can say return data that have multiple categories. 我需要能够查询数据,以便我可以说返回具有多个类别的数据。 I have tried a few different ways but so far can't figure it out.
我尝试了几种不同的方法,但到目前为止还无法解决这个问题。 I am sure it is simple so hoping someone can help out.
我确信它很简单,所以希望有人可以提供帮助。
Here is where I got but can't figure out what I need in the where clause to make it work. 这是我得到的地方,但无法弄清楚在where子句中我需要什么才能使它工作。 If I only need one category it works but with 2 it does not.
如果我只需要一个类别它可以工作,但有2个它不需要。
SELECT distinct a.entry_id, b.title
FROM exp_channel_data as a
LEFT JOIN exp_channel_titles as b
ON a.entry_id = b.entry_id
LEFT JOIN exp_category_posts as c
ON a.entry_id = c.entry_id
WHERE c.cat_id = 10 and c.cat_id = 30
You can use a query like the following in order to get entry_id
values being related to both cat_id
values: 您可以使用一个查询类似以下,以获得
entry_id
值被涉及到两个 cat_id
值:
SELECT entry_id
FROM category_posts
WHERE cat_id IN (10, 30)
GROUP BY entry_id
HAVING COUNT(DISTINCT cat_id) = 2
Now you can use the above query as a derived table and JOIN
to it in order to get the expected result: 现在,您可以将上述查询用作派生表并对其进行
JOIN
以获得预期结果:
SELECT distinct a.entry_id, b.title
FROM exp_channel_data as a
LEFT JOIN exp_channel_titles as b ON a.entry_id = b.entry_id
LEFT JOIN (
... above query here
) AS c ON a.entry_id = c.entry_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.