douanrang4728 2016-05-31 02:18
浏览 11

从mysql中的另一个表获取数据

I have a table with an item_id and some other fields.

item_id,name,address,postcode

I also have a table of messages that relate to an item_id

item_id,user_id,message

What I am trying to do is make a query that selects all rows in a specific postcode (not an issue there)

but also return something (0 or 1 for example) if the user that is logged in also has messages associated with the item

so I have a basic query like this:

select item_id,name,address,postcode from items where postcode in ('3000')

but I want to incorporate the messages table somehow so that I am left with a flag to show that the user_id has or has not sent a message related to the item

How can I do this?

I tried a left join, but that will only show results where the user has messages, whereas I want the result regardless of if the user actually sent a message, I just want to know if they did or not.

  • 写回答

1条回答 默认 最新

  • douju1928 2016-05-31 02:54
    关注

    Use an IF condition to check the message field IF(message.message <>'', 1, 0) as flag

    SELECT 
        items.item_id,name,address,postcode, 
        IF(message.message <>'', 1, 0) as flag, message 
    FROM items 
    LEFT JOIN message ON items.item_id = message.item_id 
    WHERE postcode in ('3000')
    

    Hope this will help.

    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?