2015-12-07 170 views
0

我有多個表如下:MySQL查詢,以避免重複結果

表1:產品

+-----+----------+--------+---------------------+ 
| id | biz_id | name | message   | 
+-----+----------+--------+---------------------+ 
| 1 | 1  | test1 | One tow three  | 
| 2 | 1  | test1 | One tow three  | 
| 3 | 1  | test1 | One tow three  | 
| 4 | 2  | test2 | hello world   | 
| 5 | 2  | test2 | hello world   | 
+-----+----------+--------+---------------------+ 

表2:圖片

+-----+----------+--------------+-------------------+ 
| id | biz_id | product_id | path   | 
+-----+----------+--------------+-------------------+ 
| 1 | 1  | 1   | img/qwert1.jpg | 
| 2 | 1  | 2   | img/qwert2.jpg | 
| 3 | 1  | 3   | img/qwert3.jpg | 
| 4 | 2  | 4   | img/qwery4.jpg | 
| 5 | 2  | 5   | img/qwert5.jpg | 
+-----+----------+--------------+-------------------+ 

如何避免在連接多個表時在mysql中重複?

我的查詢是加入這兩個表,以便我想避免重複的產品(獲取Distint產品的名稱)並獲取與該產品相關的所有圖像(例如Product> name - test1 has images qwert1.jpg,qwert2.jpg ,qwert2.jpg)

+0

將所期望的結果是什麼樣的? – Strawberry

回答

0
SELECT p.name, GROUP_CONCAT(i.path) 
    FROM product AS p 
    INNER JOIN images AS i ON p.id = i.product_id 
    GROUP BY p.name; 

請注意,這不是標準的SQL,但大多數DBMS提供此功能(儘管關鍵字可能會有點不同)。

0

簡單連接應該做的所有的事情

select p.name as Name, i.message as IMG from Images 
left join Product p 
on i.biz_id=p.biz_id 
group by p.name; 
0

使用left joinGROUP_CONCATgroup by

select p.name name,GROUP_CONCAT(i.path) img 
from Images i left join Product p 
on i.biz_id=p.biz_id 
group by i.product_id