dongtangjie0495 2015-08-31 18:54
浏览 49
已采纳

从表A中获取随机结果(如果它存在于表B中)并满足查询中的WHERE语句

I have two tables; one table with users, a second table contains the categories.

On the site's frontend are a bunch of filters to filter users. One of the filters is a dropdown with checkboxes that have category values. E.g: admin, user, publisher etc can be selected.

When multiple checkboxes have been checked get a random user from users but only random user that has all selected categories.

The users have an unique id. The categories have an unique id, the category value (admin, publisher, user etc) and the user-id so it can be tied together I think.

Important note:

($value = the posted value from checkbox, also keep in mind that the categories.category = $value part is added dynamically depending on the amount of selections, I append that using a foreach)

My current query:

$sql = "SELECT users.*, categories.*
       FROM users
       INNER JOIN categories
       ON users.id = categories.user_id
       WHERE categories.category = '$value' AND 
             categories.category = '$value' 
             --> continues endlessly depending on the amount of selections that have been made.
       ORDER BY RAND()
       LIMIT 0,1";

For some reason this only works when one checkbox is selected. When a second one, or more a selected, it breaks, no errors, it just simply doesn't find any result.

I hope my question is clear, if you need any future information, please let me know!

  • 写回答

1条回答 默认 最新

  • dsfsdf7852 2015-08-31 19:11
    关注

    Assuming that $values is an array of the category IDs (I'll assume integers), you could run a query like:

    SELECT
      users.*
    FROM
      users
    INNER JOIN
      categories ON users.id = categories.user_id
    WHERE
      categories.category IN (" . implode(',', $values) . ")
    GROUP BY
      users.id
    HAVING
      COUNT(DISTINCT categories.category) >= " . count($values) . "
    ORDER BY
      RAND()
    LIMIT 1
    

    I've made an example fiddle.

    Edit

    If the categories are strings then you'd need to ensure proper quotation, i.e. change the WHERE to:

    categories.category IN ('" . implode("','", $values) . "')
    

    Or if using prepared statements (which is ideal) you'd bind implode(',', $values) using:

    FIND_IN_SET(categories.category, ?) != 0
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 outlook无法配置成功
  • ¥15 Pwm双极模式H桥驱动控制电机
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换