简体   繁体   English

MySQL-JOIN产生“额外”结果吗?

[英]MySQL - JOIN producing “extra” results?

It would be rather difficult to explain this issue without showing you what I've got, so we'll start with that: 不向您展示我所拥有的东西就很难解释这个问题,因此我们将从这一点开始:

http://i.stack.imgur.com/scpv6.png

http://i.stack.imgur.com/XZFQR.png

Query: 查询:

SELECT goodies.title FROM `goodies` LEFT JOIN `goody_images`
ON goodies.id=goody_images.goodie_id

Raw Result: 原始结果:

candy 糖果
candy 糖果
hats 帽子

The issue: 问题:

It produces an extra result per each joined value. 每个连接值产生一个额外的结果。 Because two of the entires in goody_images have the a goodie_id of 1 , it prints the corresponding title from goodies twice, hence why we see the result candy twice. 由于两人在goody_images的entires的有1所涉及的goodie_id,它打印从糖果相应称号的两倍,因此,为什么我们看到的结果糖果的两倍。 I instead need it to only give my the title once, regardless of the number of matching JOIN results. 相反,无论匹配的JOIN结果有多少,我都只需要给它一次标题即可。

Is this possible, or am I better off running two separate queries? 这可能吗,还是我最好运行两个单独的查询?

In context of PHP, I'm trying to get two values: 在PHP的上下文中,我试图获得两个值:

-One with the title, -一个标题,
-And and an array with the matching images. -并且具有匹配图像的数组。

The programming for all of that is already complete are perfectly operational - The issue simply lies in getting the results properly. 所有这一切的编程已经完成,可以完美地操作-问题仅在于正确获得结果。

+ The above query was abbreviated for simplicity + 为简化起见,以上查询已缩写

Either use distinct 要么使用distinct

SELECT distinct goodies.title 
FROM `goodies` 
LEFT JOIN `goody_images` ON goodies.id=goody_images.goodie_id

or group by group by

SELECT goodies.title 
FROM `goodies` 
LEFT JOIN `goody_images` ON goodies.id=goody_images.goodie_id
GROUP BY goodies.title 

It is not showing extra record it showing candy two time because goodie_id 1 has two images but if you want to select title only then you can use 它没有显示多余的记录,而是两次显示糖果,因为goodie_id 1有两个图像,但是如果您只想选择标题,则可以使用

SELECT goodies.title FROM `goodies` LEFT JOIN `goody_images`
ON goodies.id=goody_images.goodie_id group by goodies.title

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM