drzrzzkh462254 2018-10-08 12:13
浏览 182
已采纳

SQL:选择与另一个表中的内容匹配的所有行

I am trying to write a query like this (hopefully with only one Query): Select all messages from inbox table where the "SenderNumber" of the message is found in "Sentitems" table and the CreatorID is 'Martin'

For example my inbox table looks like this:

| SenderNumber   |   TextMessage    |
    11111111       Yes, nice world!
    22222222         Howdy folks!

And my sentitems table looks very similar

| DestinationNumber  | TextMessage |  CreatorID
      11111111         Hello world?    Martin
      22222222          How you do?     John

I would like to get all message from Inbox table with this condition - there is an entry for this "SenderNumber" / "DestinationNumber" in my sentitems table and the CreatorID is 'Martin'.

So in this case it would return this entry because the creatorID for the other number is not 'Martin' but 'John'

| SenderNumber   |   TextMessage    |
    11111111       Yes, nice world!
  • 写回答

1条回答 默认 最新

  • dpkt31779 2018-10-08 12:26
    关注

    Try this one :

    SELECT i.SenderNumber, i.TextMessage
    FROM inbox as i
    INNER JOIN sentitems as s ON s.DestinationNumber = i.SenderNumber AND s.CreatorID = 'Martin'
    

    The logic is :

    1. You select what you want, here SenderNumber and TextMessage from the table inbox
    2. Now you use an INNER JOIN with the table sentitems and two conditions : DestinationNumber from table sentitems and SenderNumber from table inbox are the same + CreatorID with the value you want, here 'Martin'

    Using INNER JOIN will return only the result that respect the two conditions. For more information, take a look to the documentation : https://sql.sh/cours/jointures/inner-join

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

报告相同问题?

悬赏问题

  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,