Taking into account the following example tables:
USERS:
id_user | name |
---|---|
1 | Paul |
2 | Caroline |
TRAVEL:
id_travel | id_user |
---|---|
1 | 1 |
2 | 1 |
3 | 2 |
TRAVEL_DAYS:
id_tdays | id_travel | day_has_activities |
---|---|---|
1 | 1 | no |
2 | 1 | no |
3 | 1 | yes |
4 | 2 | no |
5 | 2 | no |
6 | 3 | no |
7 | 3 | yes |
8 | 4 | yes |
If I do the following query:
SELECT
t.id_travel,
u.name,
td.day_has_activities
FROM travel t
left join users u on u.id_user = t.id_user
left join travel_days td on td.id_travel = t.id_travel
Since trip number one has three days and trip two, as well as trip three, have two days each the result would be something like this:
id_travel | id_user | day_has_activities |
---|---|---|
1 | Paul | no |
1 | Paul | no |
1 | Paul | yes |
2 | Paul | no |
2 | Paul | no |
3 | Caroline | no |
3 | Caroline | yes |
I need to have unique trip rows, so I thought about using DISTINC but the has_activities field shows me "yes" or "no" randomly.
I need to know for each trip if it contains any days with activities so the perfect result would be this :
id_travel | id_user | travel_has_activities |
---|---|---|
1 | Paul | yes |
2 | Paul | no |
3 | Caroline | yes |
I tried something like this, but it doesn’t runs:
SELECT
t.id_travel,
u.name,
if ((select count(td.day_has_activities) from t where td.day_has_activities like 'yes') > 0, 'yes', 'no') as travel_has_activities
FROM travel t
left join users u on u.id_user = t.id_user
left join travel_days td on td.id_travel = t.id_travel
2
Answers
You should obtain the maximum value of day_has_activities for each id_travel and then join it with your tables using a
LEFT JOIN
.Demo here
CTE part, I used your query to joins table, and second part I used self join and exist function to check yes values exist in previous table or not and group by according to first and second table