简体   繁体   English

来自和列的MYSQL SELECT DISTINCT值以及来自另一个的对应值

[英]MYSQL SELECT DISTINCT value from and column and its corresponding value from another

I have a column in a database which i use the below code to get the distinct values from that column 我在数据库中有一列,我使用下面的代码从该列获取不同的值

"SELECT DISTINCT category FROM galleryinfo"

I have another column with the path to the relevant image. 我还有另一列包含相关图像的路径。

So my question is how do i get the unique/distinct values from category and it corresponding path from the other column. 所以我的问题是如何从类别中获取唯一/不同值,并从另一列获取其对应的路径。

Thanks in advance for any help. 在此先感谢您的帮助。

id    path           category
1     img1           car
2     img2           car
3     img3           truck
4     img4           truck
5     img5           bike

The result i require would be 我需要的结果是

img1   car     
img3   truck   
img5   bike

You can use a GROUP BY query to reduce the result to one row per distinct category: 您可以使用GROUP BY查询将结果减少为每个不同类别的一行:

SELECT category, path FROM galleryinfo GROUP BY category

The problem with this is that it's arbitrary which path this query returns. 这里的问题是,它的任意该查询返回一个路径。 In fact, in most SQL implementations, this is an illegal query and results in an error. 实际上,在大多数SQL实现中,这是非法查询并导致错误。 MySQL is more lenient, but it will return an arbitrary path from those matching the category (in practice, it chooses the path from the first row with respect to physical storage, but this is not documented or guaranteed). MySQL更为宽容,但它会从与该类别匹配的那些返回返回任意路径(实际上,它相对于物理存储从第一行中选择路径,但这没有记录或保证)。

You can choose either the MIN(path) or MAX(path) , or concatenate all paths per category together into one string with GROUP_CONCAT(path) , but that's about it. 您可以选择MIN(path)MAX(path) ,也可以使用GROUP_CONCAT(path)每个类别的所有路径连接到一个字符串中,仅此而已。

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

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