Home  >  Q&A  >  body text

SQL left join using where clause to filter empty fields

<p>I have two tables, one is the Users table and the other is the Token table. I want to join these two tables to see which users have verified their tokens and which have not. There is a foreign key in the token table that contains the user ID. </p> <p>Now I'm using a left join to join the user IDs and trying to check if there is no validation. The query statement is as follows: </p> <pre class="brush:php;toolbar:false;">SELECT name, verified FROM users LEFT JOIN tokens ON users.ID = tokens.UID WHERE verified = false</pre> <p>Suppose I have the following two tables: </p> <pre class="brush:php;toolbar:false;">ID | Name 0 | Joe 1 | Sally 2 | Dave 3 | John</pre> <p>Then, the token table is as follows: </p> <pre class="brush:php;toolbar:false;">ID | UID | Verifed 0 | 1 | 0 1 | 2 | 0 2 | 3 | 1</pre> <p>As you can see, Joe has no records in the second table. I want to join these two tables and even if Joe has no record in the second table, I want it to be treated as false/null. When I run the query to find unauthenticated users, only 2 entries of data are returned. </p> <pre class="brush:php;toolbar:false;">Name | Verified Sally | 0 Dave | 0</pre> <p>If I remove the where clause, the result will be as follows: </p> <pre class="brush:php;toolbar:false;">Name | Verified Sally | 0 Dave | 0 John | 1 Joe | NULL</pre> <p>As you can see, Joe has a null value at the bottom, but I want it to be treated as unvalidated. How should I write a query to get the following data: </p> <pre class="brush:php;toolbar:false;">Name | Verified Sally | 0 Dave | 0 Joe | NULL</pre> <p>Or just the following query statement, the result is 3. The current query result is 2. </p> <pre class="brush:php;toolbar:false;">SELECT count(*) FROM users LEFT JOIN tokens ON users.ID = tokens.UID WHERE verified = false</pre> <p><br /></p>
P粉511985082P粉511985082433 days ago506

reply all(1)I'll reply

  • P粉322106755

    P粉3221067552023-08-14 13:23:45

    WHERE verified = false 或 verified is null

    reply
    0
  • Cancelreply