MySQL连接两表查询
我有两张桌子,产品和产品图片 产品表MySQL连接两表查询,mysql,Mysql,我有两张桌子,产品和产品图片 产品表 |----------------Table:product-| |ID | tr_productname | |---|--------------------------| | 1 | Computer | | 2 | Telephone | | 3 | Television | | 4 | Mouse |
|----------------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 |
|------------------------------|--------------|
结果强>
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的产品尝试此
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
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
尝试按
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
使用“分组依据”时,仅显示“分组依据”中涉及的值。在您的案例中,您已经根据productimages表进行了分组,在该表中,不存在4值。因此,请在group by中使用product.id
我猜您正在查找每个产品的所有图像,如果是,请尝试将组链接(imageurl)作为imageurl,我尝试加入并选择,但没有成功。它工作,但第四记录似乎没有。需要一个产品的productimages记录。我要列出所有产品。没有将组_concat(imageurl)作为imageurl工作。仅代码或仅查询的答案通常不是“优质”答案。请提供一些解释,说明你为什么认为这回答了这个问题。