douxu5233 2014-04-14 07:12
浏览 799

在mySQL中减去两个查询结果

I have 2 queries which gives all records(including the booked ones) and gives out booked records only. I wanted to subtract the two tables so that it only shows the unbooked records, here are the example of the query results:

Query 1:

+--------+--------+
| Number | AreaNo | 
+--------+--------+ 
|      6 |      A |  
|      6 |      B |  
|      6 |      C |  
|      7 |      A | 
|      7 |      B | 
+--------+--------+

Query 2:

+--------+--------+
| Number | AreaNo | 
+--------+--------+ 
|      6 |      B |  
|      6 |      C |   
|      7 |      B | 
+--------+--------+

Desired Results:

+--------+--------+
| Number | AreaNo | 
+--------+--------+ 
|      6 |      A |  
|      7 |      A | 
|      7 |      C | 
+--------+--------+

I know that I can't use MINUS in mySQL but I'm not sure that LEFT JOIN works in this situation. If this doesn't work, is it possible to work on the where clause?(Like if the number match, it only clear out the one with matching AreaNo). I tried this with two AND clause and it doesn't work. It clears out the results that doesnt fit either criteria. I have been doing researches over a week and nothing works. Please help, I am really desperated.

Query 1:

SELECT bookingListNo,
       areaNo 
  FROM BookingList, 
       BookingArea, 
       BookingLocation 
 WHERE bookingListNo NOT IN (SELECT bookingListNo 
                               FROM Booking 
                              WHERE bookingAreaNo IS NULL) AND 
       BookingList.bookingLocationNo = BookingLocation.bookingLocationNo AND
       BookingLocation.BookingLocationNo = BookingArea.bookingLocationNo 

Query 2:

SELECT bookingListNo, 
       areaNo 
  FROM Booking, 
       BookingArea 
 WHERE Booking.bookingAreaNo = BookingArea.bookingAreaNo
  • 写回答

4条回答 默认 最新

  • doudou890510 2014-04-14 07:16
    关注

    Check out this article for reference: http://www.sitepoint.com/understanding-sql-joins-mysql-database/

    I'm guessing a RIGHT JOIN would do the trick.

    Not exactly sure what your tables are like, but if you are joining a table with unbooked data to one that has all of our items, then you could do a query like this:

    SELECT *
    FROM all_items
    RIGHT JOIN unbooked_data ON all_items.item_id = unbooked_data.item_id
    

    When you RIGHT JOIN it only selects the items that are in the table you are joining on that have matches in the table being joined to. This should allow you to select unbooked data. If this doesn't fit your situation, including your queries in your question might help us answer your problem more directly.

    评论

报告相同问题?

悬赏问题

  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题