CS Dude
CS Dude

Reputation: 451

MySQL One to Many Select

I have a one to many relationship between Table A (The one table) and Table B (The many table).

I want to query Table A and only return entries from Table A where it has at least one row in Table B.

I thought it might be an Inner Join but I am still getting a row returned for each entry in Table 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.

I apologise that this is such a simple question I couldn't find the answer myself I assume I am wording it wrong.

Upvotes: 0

Views: 4688

Answers (4)

M Khalid Junaid
M Khalid Junaid

Reputation: 64466

To get the categories data (not images data) with at least one association in table b you can do something like below

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

Upvotes: 2

Roshan Dandgavhal
Roshan Dandgavhal

Reputation: 559

Use This query

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

Upvotes: 1

kenfire
kenfire

Reputation: 1355

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. Try using Left join if it's the opposite

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

Upvotes: 1

etsa
etsa

Reputation: 5060

You can do in several ways. One could be following. It use EXISTS in WHERE condition:

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):

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

Upvotes: 1

Related Questions