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 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大