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 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址