带有/ 2表的MySQL Query可以获得所需的结果

时间:2011-08-04 18:40:42

标签: php mysql

我正在尝试根据发布类别提取相关的帖子。因此,所有类别ID都与类别ID字段匹配。

补充说明:

我整个上午都在试验,但仍然没有运气,这就是我现在所处的位置。请注意,ON子句中的$ CatID来自上一个查询,并且值正确。

$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())
";

经过测试:

echo $CatID . $row['Category']; // Outputs 3 3 which is correct.  Category is 3 ads_cate id is also 3 for this record.

我的结果是重复和所有广告,无论类别如何。

3 个答案:

答案 0 :(得分:1)

如果每个广告都有一个类别,并假设您的ads_cate表格中有id字段:

$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()
";

答案 1 :(得分:0)

虽然我不明白您的问题,但在使用加入时,您可以使用SELECT DISTINCT来停止重复。除此之外,我不明白这个问题。

答案 2 :(得分:0)

这是我的工作代码。不得不根据bfavaretto的建议修改一些,但它现在按预期工作:

$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())";