douzhengyi5022 2019-05-23 18:12
浏览 330
已采纳

Golang中的MySQL空值

How have you solved the issue around LEFT JOIN's and null values with MySQL and Go?

For example I have two tables order and order_item. All columns have the not null attribute. An order can have 0 or more order_items. A simple select, left join query of an order without any order_items fails Row.Scan() because the order_item columns come back as null:

SELECT * FROM `order`
LEFT JOIN `order_item` USING (order_id)
WHERE `order`.order_id = '123'

I can see three solutions, none that I think are really good:

  1. Use COALESCE/IFNULL => Annoying because my select part of the query is automatically generated.
  2. Use the null values from mysql go lib => This will mean that every value in my order_item struct will be of these types.
  3. Split the query into 2 => Problem if I want a list of 50 orders with order_items, that will be 51 queries.

Any other solutions you have?

  • 写回答

1条回答 默认 最新

  • drl92080 2019-05-23 19:22
    关注

    You can use option 2 but instead of scanning into your struct and having to change the types of your struct, you can scan into temporary variables with nullable datatypes and based on the validity of those variables, copy their values into your struct with non-nullable types.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况
  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置
  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?
  • ¥15 cgictest.cgi文件无法访问
  • ¥20 删除和修改功能无法调用