简体   繁体   中英

How to use JOIN in WHERE clause in SQL statement?

Below are 2 collections - Merchants and Tokens.
Tokens is a table that holds tokens for a merchant to use.
Each merchant can have multiple tokens.

Table: Merchants
Columns:

  • Id (nvarchar, not null),
  • Name (nvarchar, not null),
  • PartnerId (nvarchar, not null),
  • Group (nvarchar, not null),
  • JoinDate (nvarchar, not null)

Table: Tokens
Columns:

  • Id (nvarchar, not null),
  • InsertDate (DateTime, not null),
  • MerchantId (nvarchar, not null),
  • TokenType (int, not null),

I am trying to write an SQL query that will fetch merchants that have inactive tokens
that were created after Aug 30, 2021 for merchants that joined after Jan 1, 2020.
Required output: merchant name, merchant join date.
Rows with duplicate data should not be displayed.

I tried to do the following:

SELECT Merchants.Name, Merchants.JoinDate
FROM Merchants
WHERE Tokens.TokenType=1 AND Tokens.InsertDate > 8/30/2021 AND Merchants.JoinDate > 1/1/2020
LIMIT 1;

However, this doesnt seem to work.
I am new to SQL and I think I should use JOIN in the WHERE clause,
but I can`t seem to make it work.
Can someone please assist?

This should be good.

SELECT DISTINCT m.Name, m.JoinDate
FROM Merchants m JOIN Tokens t ON m.Id = t.MerchantId
WHERE t.InsertDate > '8/30/2021' AND m.JoinDate > '1/1/2020' AND t.TokenType = 1

Joins are inserted in FROM statement, while in WHERE statement you need to add attribute's condictions (selection operator of relational algebra)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM