dprntkxh703029 2017-02-12 15:31
浏览 38
已采纳

限制随机返回的id,但每个id的行数未知

I want to select 5 random users out of my database and show all their food preferences.

Currently I have these tables:

CUSTOMERS
customer_id email 

FOOD_PREFERENCE
food_id food_name allergic_info

LISTING
customer_id food_id

My query has to be something similar to this:

SELECT c.email, f.food_name, f.allergic_info
FROM customers c, food_preference f, listing l
WHERE l.customer_id=c.customer_id AND f.food_id=l.food_id
ORDER BY rand(c.customer_id) LIMIT 10

The problem is: I don't want to limit the rows that are returned, I just want to limit the different customer_id's. Buts since I have to select them randomly, I can't use math (like e.g. "WHERE customer_id < 6"). Is there a way to randomly select 5 customers and return all their food_preferences within the same query?

  • 写回答

2条回答 默认 最新

  • dongzhuzhou4504 2017-02-12 15:38
    关注

    First, never use commas in the FROM clause. Always use explicit JOIN syntax.

    So, your query should be:

    SELECT c.email, f.food_name, f.allergic_info
    FROM listing l JOIN
         customers c  
         ON l.customer_id = c.customer_id JOIN
         food_preference f
         ON f.food_id = l.food_id
    ORDER BY rand(c.customer_id)  -- I don't know why you are providing a see here
    LIMIT 10;
    

    If all customers have food preferences, just put the limit in a subquery:

    SELECT c.email, f.food_name, f.allergic_info
    FROM listing l JOIN
         (SELECT c.*
          FROM customers c  
          ORDER BY rand()
          LIMIT 5
         ) c
         ON l.customer_id = c.customer_id JOIN
         food_preference f
         ON f.food_id = l.food_id;
    

    If not all customers are in listing and you only want customers in listing, then you can add another join:

    SELECT c.email, f.food_name, f.allergic_info
    FROM listing l JOIN
         customers c
         ON l.customer_id = c.customer_id JOIN
         food_preference f
         ON f.food_id = l.food_id JOIN
         (SELECT customer_id
          FROM (SELECT DISTINCT customer_id FROM LISTING) lc
          ORDER BY rand()
          LIMIT 5
         ) lc
         ON l.customer_id = lc.customer_id
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图