doupingzhi9674 2012-04-18 23:40
浏览 50
已采纳

MySQL Complex查询无法返回正确的结果

I have the following query:

'SELECT * FROM posts LEFT JOIN taxi ON taxi.taxiID = posts.postID
    WHERE (taxi.value = 1 AND taxi.userID ='.$userID.') 
    AND ??????????????
    ORDER BY taxi.ID DESC
    LIMIT 10'

The way the site works is the user can tag posts as being "liked". When a post is liked, the taxi table is given a new row with taxiID being the same as postID, userID to store the user that liked the post, and value which is set to 1. Disliking a post sets value to 0.

I want to display all posts where value is 1 and userID is $userID - check. However, I also want the query to display all the posts where the user hasn't liked a post yet. Thing is, if the user hasn't liked a post yet, userID is NULL with a corresponding value of NULL. If I query for that, I'll be skipping those posts that other users have liked but the user hasn't.

Here's the taxi table:

ID    taxiID    userID    value
1     1         1         1
2     1         6         1
3     1         4         0
4     2         1         0
5     2         6         1
6     2         4         0
7     3         6         1
8     3         4         0

Assuming $userID is 1, my query ought to display taxiID 1 and 3 (because user 1 liked ID 1 AND hasn't liked or disliked taxiID 3.

The code I've posted will only result in displaying taxiID 1.

The question is, what is my missing line in my query supposed to be given the above?

  • 写回答

3条回答 默认 最新

  • dro62273 2012-04-18 23:55
    关注

    It seems you want to find all taxiID that the use has not disliked:

    SELECT taxiID 
    FROM taxi
    GROUP BY taxiID
    HAVING taxiID NOT IN 
          ( SELECT taxiID
            FROM taxi 
            WHERE userID = '.$userID.'
              AND value = 0
          )
    ORDER BY taxiID DESC
    LIMIT 10
    

    Test in SQL-Fiddle


    You probably have a post table, so it would be better to use:

    SELECT *                               --- whatever columns from `post` table
    FROM post
    WHERE postID NOT IN                     
          ( SELECT taxiID
            FROM taxi 
            WHERE userID = '.$userID.'
              AND value = 0
          )
    ORDER BY postID 
    LIMIT 10
    

    If that taxi.taxiID means postID, then you should rename it to taxi.postID. It's very confusing as it is.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 请问如何在openpcdet上对KITTI数据集的测试集进行结果评估?
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错