Select 来自两个表的相同值对

Select the same pairs of values from two tables

我的数据库中有 4 个 MySQL table:

  1. Users (uid, 名称)
  2. Shops (shopId, shopName)
  3. Reviews (ReviewId, text, userId, shopId, rate, date)
  4. TransactionHistory (transactionId, userId, shopId, Amount, date)

用户在 Reviews table 的商店中写下他们的评论。并且部分店铺的用户支付记录保存在TransactionHistorytable中。

我需要select一段时间内所有用户的评论,如果该用户在同一时间段内在该商店付款。

  1. Select userId, shopId, rate, text, date from Review where date between "01.01.2019" and "01.02.2019" where shopId in (select distinct(shopId) from Shops)

  2. Select userId, shopId, date from TransactionHistory where date between "01.01.2019" and "01.02.2019"

所以我有两个结果集,一些记录具有相同的对 (userId, shopId) - 这就是我想要得到的:来自 1 SQL 请求的所有记录,它们对 (userId, shopId)出现在 2 SQL 查询中。

如果我没理解错的话,你只需要一个像这样的连接语句:

   SELECT * FROM t1 LEFT JOIN (t2, t3, t4)
                 ON (t2.a = t1.a AND t3.b = t1.b AND t4.c = t1.c)

这是资源https://dev.mysql.com/doc/refman/8.0/en/join.html

在你的情况下,在 on 语句中将是你想要相等的。

Select userId, shopId, rate, text, date from Review r join TransactionHistory th on (r.userId == th.userId and r.shopId == th.shopId) where r.date between "01.01.2019" and "01.02.2019" where r.shopId in (select distinct(shopId) from Shops)
SELECT u.uid, u.name as userName, u.surname, s.name, rate, review, c.amount FROM `rsamazingapp.rsamazingapp.reviews` as r 
INNER JOIN `rsamazingapp.cashbacks` as c ON (r.uid = c.uid and r.shop_id = c.shop_id) 
INNER JOIN `rsamazingapp.shops` as s on (r.shop_id = s.shop_id)
INNER JOIN `rsamazingapp.users` as u on (r.uid = u.uid)
where r.shop_id in (select distinct shop_id from `rsamazingapp.shops`)
order by rate desc