Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

mysql - Where clause for only one table in a left join

I have two tables, the first is 'actions' which has columns 'id' and 'actionname', the second is 'completedactions' which has 'userid' and 'actionid'. They look as follows:

Table: actions

 id | actionname
 ==============
  1 | An action
  2 | Another
  3 | ect
  4 | ect

actions is a table of actions a user can make

-

Table: completedactions

 userid | actionid
 ==============
   1    |  1
   1    |  2
   1    |  3
   2    |  3
   3    |  2
   3    |  4

completedactions holds the userid and action id for each action made

I want to join the tables to give a list of all actions and which of those actions have been made by a given user, specified somewhere in the query. So from this example I'd like to see something like:

 id | actionname | Complete by userid=1?
 =======================================
  1 | An action  | 1
  2 | Another    | 1
  3 | ect        | 1
  4 | ect        | Null

I've tried a left join and have managed to get a list of all actions but there are duplicate entries when multiple users have taken an action, one for each user to have made the action. I then added a where clause at the end compledtedactions.userid="1" but I then lose all actions that haven't been made by that user.

I can't seem to have a where clause for only one table in the left join so how else should I be going about this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try using your WHERE condition in your ON() clause instead, i.e., ON (c.actionid = a.id AND c.user_id = 1).

The WHERE filter will apply on the whole resultset, while an additional condition in the join will join the matched results and give null for non-matched results.

SELECT a.*,c.user_id FROM 
actions a 
LEFT JOIN completedactions c 
ON (c.actionid = a.id AND c.user_id = 1)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...