Ramil
Ramil

Reputation: 91

How to [MySQL] select users with records

I have these tables:

users:

|user_id|user_name|
|-------|---------|
|   1   |  John   |
|-------|---------|
|   2   |  Mark   |
|-------|---------|
|   3   |  Paul   |
|-------|---------|

records:

| record_id | user_id |    records   |
|-----------|---------|--------------|
|    1      |    3    | lorem ipsum  |
|-----------|---------|--------------|
|    2      |    3    | dolor sit    |
|-----------|---------|--------------|
|    3      |    3    | consectetur  |
|-----------|---------|--------------|
|    4      |    1    | adipisicing  |
|-----------|---------|--------------|
|    5      |    3    | eiusmod      |
|-----------|---------|--------------|
|    6      |    1    | consectetur  |
|-----------|---------|--------------|

What I want is to select users who have records. In this case, only John and Paul should return.

Upvotes: 1

Views: 81

Answers (2)

qooplmao
qooplmao

Reputation: 17759

SELECT u.user_name, r.records FROM users as u, records as r where u.user_id = r.user_id

Upvotes: 0

cegfault
cegfault

Reputation: 6632

Using a subquery:

SELECT user_name FROM users WHERE user_id IN (SELECT DISTINCT user_id FROM records)

Or using an INNER JOIN:

SELECT u.user_name FROM users u
INNER JOIN records r ON u.user_id=r.user_id
GROUP BY u.user_name

Upvotes: 1

Related Questions