簡體   English   中英

如何在不重復列值多次的情況下聯接表?

[英]How to join tables without repeating a column value multiple times?

我有3張桌子:圖像,顏色和標簽。 每個圖像具有2種顏色和至少1個標簽。 我希望我的用戶單獨搜索標簽或/和顏色。

問題是,當我聯接表時,會多次獲得在列中具有相同值的行。

SELECT images.id, tag, color
FROM images
JOIN tags ON tags.image_id = images.id
JOIN colors ON colors.image_id = images.id
WHERE images.id = 1

I get:
image_id: 1, tag: sky, color: blue
image_id: 1, tag: cloud, color: blue
image_id: 1, tag: sky, color: white
image_id: 1, tag: cloud, color: white

But the result I want is something like:
image_id: 1, tag1: sky, tag2: cloud, color1: blue, color2: white

這有可能嗎? 還是應該更改數據庫設計?

函數group_concat()會將所有標簽或顏色值放入一個字段,並使用您喜歡的分隔符:

SELECT images.id, group_concat(distinct tag separator ', ') as tags,
       group_concat(distinct color separator ', ') as colors
FROM images
left JOIN tags ON tags.image_id = images.id
left JOIN colors ON colors.image_id = images.id
WHERE images.id = 1
group by images.id

(嚴格地說,在這種情況下,不需要group by ,因為您將過濾到一個組。但是您可能想要消除where子句,並在多個ID中看到它。)

distinct關鍵字可防止重復,這一點很重要,因為查詢會在標簽和顏色之間產生笛卡爾積。 如果您有4個標簽和3種顏色,則查詢將為每個ID生成4 * 3 = 12行。 我確實將連接更改為左外部連接,因此您將看到缺少標簽或顏色的ID。

你居然要求1tag1 , TAG2 ,顏色1 , and color2`作為輸出。 好吧,如果最多有兩個值,那么您很幸運:

SELECT images.id,
       min(tag) as tag1, max(tag) as tag2,
       min(color) as color1, max(color) as color2
FROM images
left JOIN tags ON tags.image_id = images.id
left JOIN colors ON colors.image_id = images.id
WHERE images.id = 1
group by images.id

使用更多顏色或標簽時,您會遇到問題。 SQL查詢具有固定數量的列-也就是說,不能僅由於將新顏色添加到ID上而添加另一列。 另外,在MySQL中,很難枚舉事物(可能,但不是標准SQL)。 如果您有兩種以上的顏色或標簽,請使用group_concat()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM