MySQL Query w/ 2 tables to get the desired results
I am trying to pull in the relate开发者_如何转开发d postings based on the posting category. So where all category ids match the category id field.
Additional clarification:
I've been experimenting all morning and still no luck, and this is where I am at now. Note the $CatID in the ON clause is from a previous query above this one and the value is correct.
$sql = "
(SELECT
a.id,
a.Price,
a.City,
a.Country,
a.Title,
a.Description,
a.Category, // contains the corresponding ads_cate.id.
a.recdate,
c.cateName,
'item' AS type FROM ads_list AS a
LEFT OUTER JOIN ads_cate AS c
ON $CatID=a.Category
WHERE to_days(now())<=(to_days(recdate)+14)
ORDER BY RAND())
";
And as tested:
echo $CatID . $row['Category']; // Outputs 3 3 which is correct. Category is 3 ads_cate id is also 3 for this record.
My results is pulling in duplicates and ALL ads regardless of Category.
If every ad has a category, and assuming your ads_cate
table has an id
field:
$sql = "
SELECT
a.id,
a.Price,
a.City,
a.Country,
a.Title,
a.Description,
a.Category, // contains the corresponding ads_cate.id.
a.recdate,
c.cateName,
'item' AS type
FROM ads_list AS a
LEFT OUTER JOIN ads_cate AS c
ON c.id=a.Category
WHERE to_days(now())<=(to_days(recdate)+14)
AND a.Category = $CatID
ORDER BY RAND()
";
Although I don't understand your question, when using join, you can use SELECT DISTINCT
to stop the duplicates. Beyond that, I don't understand the question.
This is my working code. Had to modify some based on bfavaretto's suggestion, but it's working as expected now:
$sql = "
(SELECT
a.id,
a.Price,
a.City,
a.Country,
a.Title,
a.Description,
a.Category,
a.images,
a.recdate,
a.images,
a.image2,
a.image3,
a.image4,
a.imgWidth,
a.imgHeight,
a.ftype,
c.id,
c.cateName,
a.email,
'item' AS type FROM ads_list
AS a LEFT OUTER JOIN ads_cate
AS c ON c.id=a.Category WHERE to_days(now())<=(to_days(recdate)+14) AND a.Category = $CatID ORDER BY RAND())";
精彩评论