My MySQL query keeps creating duplicate entries. I think it is to do with my join or ID values.
I am new to JOIN and I am trying to do a fairly simple JOIN and filter.
Basically I am filtering products on a product listing page.
newCatCols
+----+-----------------+-------------+
| id | sku | name |
+----+-----------------+-------------+
| 1 | 670_apple | Black |
| 2 | 670_apple | Apple |
| 3 | 670_apple | Blush |
| 4 | 670_apple | Turquoise |
| 5 | 670_apple | Light Coral |
| 10 | 640_apple_black | Apple_Black |
| 22 | 347_blush | Lime |
| 33 | 347_blush | Turquoise |
| 44 | 347_blush | Gray |
| 55 | 347_blush | Yellow |
+----+-----------------+-------------+
newCatProds
+----+-----------------+--------+------+
| id | sku | cost | cat |
+----+-----------------+--------+------+
| 1 | 670_apple | 489.55 | swar |
| 10 | 640_apple_black | 458.99 | swar |
| 22 | 347_blush | 741.44 | sig |
+----+-----------------+--------+------+
If the custom chooses Black, I want it to return colours with Black, and Apple_Black and Apple. It just duplicates listings though:
// productslisting.php?cat=swar&filter=Black
$strColourGet=mysql_real_escape_string($_GET["filter"]);
$strCatGet=mysql_real_escape_string($_GET["cat"]);
if($strColourGet=="Black"){
$checkSQL=mysql_query("
SELECT * FROM `newCatProds`
INNER JOIN `newCatCols`
ON `newCatProds`.`sku` = `newCatCols`.`sku`
WHERE (
`name` = 'Black' OR
`name` = 'Apple' OR
`name` = 'Apple_Black'
)
AND `status`='1' AND `category` = '".$strCatGet."'
ORDER BY `newCatProds`.`rank` DESC");
}
Results appear twice though. Can I somehow not have it appear twice?
710 702_appleblack 139 sig 0 8 1 1 1243 702_appleblack Apple_Black
486 613_turq 139 sig 0 124 1 1 695 613_turq Black
463 379_sapphire2 139 sig 0 46 1 1 652 379_sapphire2 Black
504 670_apple 119 sig 0 176 1 1 607 670_apple Black
463 379_sapphire2 139 sig 0 46 1 1 658 379_sapphire2 Apple_Black
So maybe a group? So the 379_sapphire2 should only appear ONCE as it has both in?
Those are all distinct results. Look at them more closely.
If you want to avoid this, instead of
SELECT * FROMdo a specific field(s) request.To get only one answer, you need to specify that field in select as distinct and create a group_by clause. You can’t create a group by with
*in select parameters.PS: I would suggest you rewrite your query something like this. It is easier to understand that way: