mysql如何选择多个表,选择*从多个表。的MySQL

本文探讨了在SQL中如何处理查询结果中的重复数据。通过JOIN操作和GROUP BY语句,配合聚合函数如GROUP_CONCAT,可以实现去除重复行并获取每个唯一ID的相关信息,例如饮品的名字、价格和照片。对于每个饮品ID,你可以选择一个照片,或者使用GROUP_CONCAT将所有照片名合并为一个字符串。但需要注意,如果照片字段包含特殊字符,可能在客户端处理时带来挑战。
摘要由CSDN通过智能技术生成

SELECT name, price, photo FROM drinks, drinks_photos WHERE drinks.id = drinks_id

yeilds 5 rows (5 arrays), photo is the only unique field in a row. name, price get repeated (here, fanta- name, price repeat 3 times.) How do i get rid of these duplicates?

Edit: I want name, price and all photo for each drink.

id name price

1. fanta 5

2. dew 4

id photo drinks_id

1. ./images/fanta-1.jpg 1

2. ./images/fanta-2.jpg 1

3. ./images/fanta-3.jpg 1

4. ./images/dew-1.jpg 2

5. ./images/dew-2.jpg 2

解决方案

What you do here is called a JOIN (although you do it implicitly because you select from multiple tables). This means, if you didn't put any conditions in your WHERE clause, you had all combinations of those tables. Only with your condition you restrict your join to those rows where the drink id matches.

But there are still X multiple rows in the result for every drink, if there are X photos with this particular drinks_id. Your statement doesn't restrict which photo(s) you want to have!

If you only want one row per drink, you have to tell SQL what you want to do if there are multiple rows with a particular drinks_id. For this you need grouping and an aggregate function. You tell SQL which entries you want to group together (for example all equal drinks_ids) and in the SELECT, you have to tell which of the distinct entries for each grouped result row should be taken. For numbers, this can be average, minimum, maximum (to name some).

In your case, I can't see the sense to query the photos for drinks if you only want one row. You probably thought you could have an array of photos in your result for each drink, but SQL can't do this. If you only want any photo and you don't care which you'll get, just group by the drinks_id (in order to get only one row per drink):

SELECT name, price, photo

FROM drinks, drinks_photos

WHERE drinks.id = drinks_id

GROUP BY drinks_id

name price photo

fanta 5 ./images/fanta-1.jpg

dew 4 ./images/dew-1.jpg

In MySQL, we also have GROUP_CONCAT, if you want the file names to be concatenated to one single string:

SELECT name, price, GROUP_CONCAT(photo, ',')

FROM drinks, drinks_photos

WHERE drinks.id = drinks_id

GROUP BY drinks_id

name price photo

fanta 5 ./images/fanta-1.jpg,./images/fanta-2.jpg,./images/fanta-3.jpg

dew 4 ./images/dew-1.jpg,./images/dew-2.jpg

However, this can get dangerous if you have , within the field values, since most likely you want to split this again on the client side. It is also not a standard SQL aggregate function.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值