doujiang1832 2017-05-17 14:54
浏览 54

MySQL:从没有关系的多个表中进行选择

First post, be gentle! My SQL knowledge is average, at best.

I have 2 tables with no direct relationship to each other.

  • TableA ("CustomerWishList") with columns "bookID", other-book-data, etc etc etc
  • TableB ("CustomerOwned") with columns - "bookID", other-book-data, etc etc etc

A book could be in one, both, or none of those tables.

I need to create SQL statement that counts the number of "bookID='data'" occurrences in either TableA or TableB.

So far using PHP I'm searching TableA "bookID" column first, and then if nothing found, searching TableB "bookID" column next ... it works, but is inefficient, and am convinced there must be a better way.

JOIN statements don't seem to apply here? - I could be wrong.


UPDATED

Psuedo PHP code I'm currently using:

$total=SELECT COUNT(*) FROM CustomerWishList WHERE BOOKID=1234

if ($total==0) {
    $total2=SELECT COUNT(*) FROM CustomerOwned WHERE BOOKID=1234
}  
return $total2;
  • 写回答

1条回答 默认 最新

  • douxun1934 2017-05-17 15:00
    关注

    Below query would give you count of book ids which are only in table A:

    SELECT count(1) as `count`
    FROM tableA
    WHERE NOT EXISTS
     (SELECT bookID FROM tableB WHERE bookID = tableA.bookID);
    

    Similarly, following query would give you count of book ids which are only in table B:

    SELECT count(1) as `count`
    FROM tableB
    WHERE NOT EXISTS
     (SELECT bookID FROM tableA WHERE bookID = tableB.bookID);
    

    Now, if you want to add these two then you can use the following query:

    SELECT `a.count` + `b.count`
    FROM ( 
     SELECT count(1) as `count`
     FROM tableA
     WHERE NOT EXISTS
      (SELECT bookID FROM tableB WHERE bookID = tableA.bookID)
     ) a,
    (
     SELECT count(1) as `count`
     FROM tableB
     WHERE NOT EXISTS
      (SELECT bookID FROM tableA WHERE bookID = tableB.bookID);
    ) b;
    
    评论

报告相同问题?

悬赏问题

  • ¥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#的问题,如何解决?