其他表中没有外键的SQL查询

时间:2017-10-24 09:40:51

标签: mysql

我有MySQL查询的问题,我有两个表 - 优惠和出价:

offers                       bids

id status                  id offer_id user_id
1  new                     1     1        1
2  new                     2     1        2
3  rejected                3     2        1    
4  accepted                4     4        4
5  new                     5     5        2
6  new                     6     6        3
7  new                     7     7        1

假设user_id = 2,我需要此user_id的所有商品(来自餐桌优惠),其中status =“new”,但没有这些商品的出价(没有商品1和商品5)

我尝试过“不存在”但没有太大成功。像:

SELECT distinct o.*
FROM offers o 
LEFT JOIN bids AS b 
ON o.id = b.offer_id
WHERE o.status = "new" AND (b.user_id!=2 
OR NOT EXISTS (SELECT * FROM  offers off WHERE b.offer_id = off.id))

类似(当没有其他用户出价相同时,我可以得到结果), 但是我无法得到我需要的东西。

编辑:

在这种情况下作为输出我需要带ID的优惠:

2 6 7(提供3和4不是“新”以及用户已经出价的优惠1和5)

3 个答案:

答案 0 :(得分:1)

你不需要在这里加入。它非常简单

  • 选择状态为new
  • 的商品
  • 排除user = 2出价
  • 的优惠

查询:

SELECT * FROM offers o
WHERE o.`status` = 'new' AND
    o.id NOT IN (SELECT offer_id from bids b WHERE b.user_id = 2)

答案 1 :(得分:0)

this.users = [...this.users , ...this.usersnew];

答案 2 :(得分:0)

这应该有效:

SELECT distinct o.*
FROM offers o
WHERE o.status = "new" AND
      o.id not in (select offer_id from bids where user_id = 2);

如果要显示所有用户,请尝试以下查询:

SELECT distinct o.*
    FROM offers o 
    Inner JOIN bids AS b 
    ON o.id = b.offer_id
    WHERE o.status = "new" AND              
Group by b.user_id
having o.id not in (select offer_id from bids b1 where b1.user_id = b.user_id);