我的数据库中有4个MySQL表:
Users
(uid,名称)Shops
(shopId,shopName)Reviews
(评论ID,文本,userId,shopId,费率,日期)TransactionHistory
(交易ID,用户ID,商店ID,金额,日期)用户在Reviews
表中的商店中写下他们的评论。某些商店中的用户付款历史记录保存在TransactionHistory
表中。
如果某个用户在同一时间在该商店付款,则需要选择一段时间内所有用户的评论。
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)
Select userId, shopId, date from TransactionHistory where date between "01.01.2019" and "01.02.2019"
所以我有两个结果集,一些记录具有相同的对(userId,shopId)-这就是我想要得到的:来自1个SQL请求的所有记录,在2个SQL查询中存在一对(userId,shopId)
答案 0 :(得分:2)
如果我理解的没错,那么您只需要一个如下的join语句:
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)
答案 1 :(得分:0)
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