挑战:如何在随机或任意选择客户名称时列出与客户名称相关的所有信用卡

问题描述 投票:1回答:2

我很难搞清楚这个问题。假设有一个客户名单和与之相关的信用卡列表,我想显示与他们相关的信用卡,但是随意或随机选择。我尝试手动硬编码名称,但我希望查询随机取名。

我尝试手动硬编码名称,但我希望查询随机取名。

MYSQL:

SELECT credit_card.`CreditCard#` AS `Creditcard Number`,  customer.customername AS `Name`
FROM credit_card, customer, account
WHERE customer.CustomerName = "Bob white" ** 

这是硬编码的

AND holds_account.`Customer#` = customer.`Customer#`
AND credit_card.`CreditCard#` = holds_account.`CreditCard#`

我想显示与他们相关的信用卡,但任意或随机选择名称。 EX客户表:A B A D.

信用卡客户编号

         A: 12321432 
         B: 234324324
         A: 1231312213
         D: 234324433

答案应该是这样的:

A 12321432
A 1231312213

名称应随机选取。

mysql sql database
2个回答
1
投票

如果要随机选择10条记录,可以使用ORDER BY RAND() LIMIT 10

示例:SELECT * FROM customer ORDER BY RAND() LIMIT 10


0
投票

首先,学习使用正确的JOIN语法编写SQL:

SELECT c.`CreditCard#`,  
       c.customername AS `Name`
FROM credit_card cc JOIN
     customer c
     ON cc.`Customer#` = c.`Customer#` 

我不认为需要accounts,但如果是的话,你可以添加它。

如果您希望所有信用汽车随机选择客户,则选择子查询中的随机客户:

SELECT c.`CreditCard#`,  
       c.customername AS `Name`
FROM credit_card cc JOIN
     (SELECT c.*
      FROM customer c
      ORDER BY rand()
      LIMIT 10
     ) c
     ON cc.`Customer#` = c.`Customer#` ;

这假设所有客户都有信用卡。如果不是这种情况,那么您可能还需要包含逻辑:

SELECT c.`CreditCard#`,  
       c.customername AS `Name`
FROM credit_card cc JOIN
     (SELECT c2.*
      FROM customer c2
      WHERE EXISTS (SELECT 1 FROM credit_card cc2 WHERE cc2.`Customer#` = c.`Customer#`)
      ORDER BY rand()
      LIMIT 10
     ) c
     ON cc.`Customer#` = c.`Customer#` ;
热门问题
推荐问题
最新问题