MySQL:多表-一对多关系,获取其子列之一不为null的列

时间:2018-08-25 08:05:54

标签: mysql sql

我在创建sql查询时需要帮助。

我想获得所有孩子的res_id都不为空的订单。

在下面的示例中,您将看到(3) [{…}, {…}, {…}] 0: {counter: 1, answer: "", approveFlag: true, options: {…}, question: "Please confirm the address of the property is", …} 1: {counter: 1, answer: "", approveFlag: true, options: {…}, question: "Please confirm the name of the seller?", …} 2: {counter: 1, answer: "", approveFlag: true, options: {…}, question: "Please confirm the number of sellers/partners?", …} order_audit.order_id有一个要 许多关系W1 temp_order_idW1_1。此W1_2还有temp_order_id res_id12。此命令32应该作为响应。

对于W1,您可以看到W2具有W2_1 resp_id。因此,不应将其拉出。

null

order_audit

+----+----------+ | id | order_id | +----+----------+ | 1 | W1 | | 2 | W2 | | 2 | W3 | +----+----------+

order_mapping

+----------+---------------+ | order_id | temp_order_id | +----------+---------------+ | W1 | W1_1 | | W1 | W1_2 | | W2 | W2_1 | | W2 | W2_2 | | W3 | W3_1 | +----------+---------------+

temp_order_table

从屏幕快照中可以看出,+---------------+--------+ | temp_order_id | res_id | +---------------+--------+ | W1_1 | 12 | | W1_2 | 32 | | W2_1 | null | | W2_2 | 33 | | W3_1 | null | +---------------+--------+ 中有一个前导空格(也许也有尾随空格)。

任何帮助将不胜感激

3 个答案:

答案 0 :(得分:3)

您可以自然地联接所有其他两个表,并检查res_id是否为空。

select oa.id, oa.order_id from order_audit oa
  where not exists (
    select * from order_mapping om
    join temp_order_table tot on
    tot.temp_order_id = om.temp_order_id
    where om.order_id = oa.order_id and tot.res_id is null
  )

这是sqlfiddle link

的链接

答案 1 :(得分:0)

您可以将NOT IN用作无效的订单

  select oa.order_id 
  from order_audit oa
  where oa.order_id NOT IN (

        select om.order_id 
        from order_mapping om
        inner join (
        select to.temp_order_id 
        from temp_order_table to 
        where to.res_id is null 
        ) t on t.temp_order_id = om.temp_order_id
  ) 

答案 2 :(得分:0)

我将使用group byhaving来解决这个问题:

select om.order_id
from order_mapping om left join
     temp_order_table tot
     on om.temp_order_id = tot.temp_order_id
group by om.order_id
having count(tot.temp_order_id) = count(tot.res_id);