简体   繁体   English

MySQL一对多选择

[英]MySQL One to Many Select

I have a one to many relationship between Table A (The one table) and Table B (The many table). 我在表A(一个表)和表B(多个表)之间存在一对多关系。

I want to query Table A and only return entries from Table A where it has at least one row in Table B. 我想查询表A,仅返回表A的条目,其中表B中至少有一行。

I thought it might be an Inner Join but I am still getting a row returned for each entry in Table B. 我以为可能是内部联接,但是我仍然在表B中为每个条目返回一行。

SELECT * FROM categories.* INNER JOIN images ON images.category_id = categories.id

That is my current query, I assume it is a WHERE clause I need to add but I do not know what. 那是我当前的查询,我假设这是我需要添加的WHERE子句,但我不知道是什么。

I apologise that this is such a simple question I couldn't find the answer myself I assume I am wording it wrong. 我很抱歉这是一个简单的问题,我想我自己说错了,我自己也找不到答案。

To get the categories data (not images data) with at least one association in table b you can do something like below 要获取表b中至少具有一个关联的类别数据(而非图像数据),您可以执行以下操作

SELECT c.* 
FROM categories c
INNER JOIN images i ON i.category_id = c.id
GROUP BY c.id
HAVING COUNT(DISTINCT i.id) > 0

Or without aggregation just distinct and join 或没有聚合只是截然不同并加入

SELECT DISTINCT  c.* 
FROM categories c
INNER JOIN images i ON i.category_id = c.id

You can do in several ways. 您可以通过多种方式进行操作。 One could be following. 一个可能正在关注。 It use EXISTS in WHERE condition: 它在WHERE条件下使用EXISTS:

SELECT * 
FROM categories
WHERE EXISTS (SELECT 1 FROM images WHERE images.category_id = categories.id)

Another can be using DISTINCT in a subquery (but I think performances are worst than former): 另一个可以在子查询中使用DISTINCT(但我认为性能比以前差):

SELECT * 
FROM categories
INNER JOIN (SELECT DISTINCT category_id FROM images) images ON images.category_id = categories.id)

You can use left/right join. 您可以使用左/右联接。

SELECT * FROM categories.* I
RIGHT JOIN images 
ON images.category_id = categories.id

In you case I supposed that Table A was categories and Table B images. 在您的情况下,我认为表A是类别,而表B是图像。 Try using Left join if it's the opposite 如果相反,请尝试使用左连接

https://www.w3schools.com/sql/sql_join_left.asp https://www.w3schools.com/sql/sql_join_left.asp

Use This query 使用此查询

SELECT c.* 
FROM categories c
INNER JOIN images i ON i.category_id = c.id
GROUP BY i.category_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM