douyouyi8878 2014-12-07 07:09
浏览 28
已采纳

Mysql - 从多个表中选择而不产生重复数据[关闭]

I have three tables and I would like to select from the tables without producing duplicates.

The table are as follows:

Customers

id     |     name   |     lastName  
---------------------------------------
1      |    john    |      doe
2      |    helen   |      keller    

Orders

The userID column is a foreign key that references John Doe, so John orders 3 items.

id     |   userID   |     order 
---------------------------------------
1      |    1       |      pizza
2      |    1       |      pasta
3      |    1       |      lasagna    

CustomerRating

The userID column is a foreign key that references John Doe, so John leaves 5 reviews.

 id     |   userID  |     rating   |  comment
-------------------------------------------------
1      |    1       |      5/5     |  was good
2      |    1       |      5/5     |  excellent
3      |    1       |      4/5     |  great
4      |    1       |      4/5     |  great
5      |    1       |      4/5     |  great

How would I select from the 3 tables where I can get a return results that look like this?

id     |     name   |     lastName    |   order      |   rating
-----------------------------------------------------------------
1      |    john    |      doe        |   pasta      |   5/5
       |            |                 |   pizza      |   5/5
       |            |                 |   lasagna    |   4/5
       |            |                 |              |   4/5
       |            |                 |              |   4/5

I've tried joining these tables, but since John has left 5 reviews and only ordered 3 times, the id, name,lastName, and order columns gets filled with duplicate data.

Thanks!

  • 写回答

3条回答 默认 最新

  • dongmo2324 2014-12-07 07:17
    关注

    I don't have any experience in MySQL but I assume that it works similar to MSSQL.

    So the format in which you are expecting the output is not possible. You can rather get the order and rating column values as comma separated

    Here is a similar kind of question that might help you

    including example based on link try something like this

    SELECT Customers.id, Customers.name, Customers.lastName, GROUP_CONCAT(Orders.order) OrderedDishes, GROUP_CONCAT(CustomerRating.rating) RatingsGiven FROM ..... rest of your query .....

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

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值