MySQL加入两个表查询

时间:2014-06-25 11:29:02

标签: mysql

我有两张桌子,产品和产品图片

产品表;

|----------------Table:product-|
|ID | tr_productname           |
|---|--------------------------|
| 1 | Computer                 |
| 2 | Telephone                |
| 3 | Television               |
| 4 | Mouse                    |
|------------------------------| 

productimages表;

|-----------Table:productimages-|
|ID | productid  |  imageurl    |
|---|------------|--------------|
| 1 |     1      | computer.jpg |
| 2 |     1      | computer2.jpg|
| 3 |     2      | telephone.jpg|
| 4 |     2      | x.jpg        |
| 5 |     2      | abc.jpg      |
| 6 |     3      | tv.jpg       |
|-------------------------------| 

我想要带有图像的列表产品,但是如果图像似乎没有记录。 我想列出所有产品。

MyQuery;

SELECT product.id, productcode, tr_productname, brand, imageurl 
FROM product 
LEFT JOIN productimages 
ON product.id = productimages.productid 
GROUP BY productimages.productid 
ORDER BY product.id DESC 

结果;

|-----------------------------------RESULT----|
|ID | tr_productname           |    imageurl  |
|---|--------------------------|--------------|
| 1 | Computer                 | computer.jpg |
| 2 | Telephone                | telephone.jpg|
| 3 | Television               | tv.jpg       |
|------------------------------|--------------| 

但没有产品" 4" ID

4 个答案:

答案 0 :(得分:1)

试试这个..

SELECT product.id, productcode, tr_productname, brand, imageurl 
FROM product 
LEFT JOIN productimages 
ON product.id = productimages.productid 
GROUP BY product.id 
ORDER BY product.id DESC 

答案 1 :(得分:1)

尝试将GROUP BY productimages.productid改为product.id,如下所示

SELECT product.id, productcode, tr_productname, brand, imageurl 
FROM product 
LEFT JOIN productimages 
ON product.id = productimages.productid 
GROUP BY product.id 
ORDER BY product.id DESC 

答案 2 :(得分:0)

当您使用分组依据时,该值仅显示在组中。在您的情况下,您已根据productimages表进行分组,在此表中,4值不存在。所以在group by中使用product.id。

SELECT product.id, productcode, tr_productname, brand, imageurl 
FROM product 
LEFT JOIN productimages 
ON product.id = productimages.productid 
GROUP BY product.id 
ORDER BY product.id DESC 

答案 3 :(得分:0)

SELECT product.id, productcode, tr_productname, brand, imageurl 
FROM product 
LEFT JOIN productimages 
ON product.id = productimages.productid 
GROUP BY product.id 
ORDER BY product.id DESC