1

I have two tables:

g1 :

id |  name  | 
1  |  G1    |
2  |  G2    |
3  |  G3    |
4  |  G4    | 
5  |  G5    | 

g_u_groups :

id | group_id | action |
1  |    2     |  view  |
2  |    3     |  add   |
3  |    2     |  view  |
4  |    3     |  view  |
5  |    1     |  add   |

I have a problem with the following query:

SELECT * 
FROM g1 
LEFT JOIN g_u_groups ON
    g_u_groups.group_id = g1.id 
    AND (g_u_groups.action = 'add' OR g_u_groups.id is null) 
ORDER BY g_u_groups.id DESC 
LIMIT 10

Now it selects only the groups which have rows in g_u_groups.

I want to order all groups by latest 'add' action but I also want to select the groups which don't have actions.

The expected results :

id |  name  | 
1  |  G1    |
3  |  G3    |
2  |  G2    |
4  |  G4    | 
5  |  G5    | 
Eloims
  • 5,106
  • 4
  • 25
  • 41
AHMED.D
  • 165
  • 2
  • 13

2 Answers2

0

Does this return the expected?

    SELECT g1.id, g1.name
    FROM g1 
    LEFT JOIN g_u_groups 
     ON g_u_groups.group_id = g1.id 
      AND g_u_groups.action = 'add' or g_u_groups.id is null 
    ORDER BY g_u_groups.id DESC, g1.id DESC
    LIMIT 10

this POST talk about sorting multiple columns, it could help you

Community
  • 1
  • 1
Shapi
  • 5,493
  • 4
  • 28
  • 39
  • same issue, but if i removed the where condition i will receive all the results my only problem will be the order of the groups. – AHMED.D Nov 22 '16 at 16:11
  • 1
    edited my post, check the link for multiple column sorting in my post – Shapi Nov 22 '16 at 16:16
0

Here is the SQL returning by latest add action also showing items without action:

SELECT * 
FROM g1 
LEFT JOIN g_u_groups ON
g_u_groups.group_id = g1.id 
where (g_u_groups.action = 'add' OR g_u_groups.id is null) 
ORDER BY g_u_groups.id DESC 
LIMIT 10;
ferec
  • 41
  • 2