MySQL SELECT使用php和两个AS id字段名称,而mysql_fetch_array()用于唯一标识它们

时间:2011-08-04 22:02:31

标签: php mysql sql while-loop

我正在运行SELECT查询,它有a.id和c.id,如下所示:

$sql = "
(SELECT
a.id,
a.Title,
a.Category,
c.id,
c.cateName FROM ads_list
AS a LEFT JOIN ads_cate
AS c ON c.id=a.Category WHERE a.Category = $CatID)"; // $CatID is defined earlier in     the script but is not pertinent to this problem.

$result = mysql_query($sql) or die(mysql_error());

while ($row = mysql_fetch_assoc($result)) { echo $row['id'] // equals c.id }

但$ row ['id']是查询中调用的最后一个id,并计算为c.id.我需要在我的while循环中获得a.id.

我的问题是如何在my()循环中唯一地获取a.id和c.id的值?

6 个答案:

答案 0 :(得分:3)

c.id列添加别名。

试试这个:

$sql = "
(SELECT
a.id,
a.Title,
a.Category,
c.id AS c_id,
c.cateName FROM ads_list
AS a LEFT JOIN ads_cate
AS c ON c.id=a.Category WHERE a.Category = $CatID)"; 


$result = mysql_query($sql) or die(mysql_error());

while ($row = mysql_fetch_assoc($result)) { 
 echo $row['id'];
 echo $row['c_id'];
}

答案 1 :(得分:2)

$sql = "
(SELECT
a.id as AID,
a.Title,
a.Category,
c.id as CID,
c.cateName FROM ads_list
AS a LEFT JOIN ads_cate
AS c ON c.id=a.Category WHERE a.Category = $CatID)";

答案 2 :(得分:2)

SELECT
  a.id AS aid,
  a.Title
  a.Category
  c.id AS cid,
  c.cateName
FROM ads_list a 
   LEFT JOIN ads_cate c ON c.id=a.Category WHERE a.Category = $CatID)

玩得开心

答案 3 :(得分:2)

您有两种选择:

1-给每个id一个别名:

SELECT
a.id AS aid,
a.Title,
a.Category,
c.id AS cid,
...

并将它们称为$ row ['aid']和$ row ['cid']。

2-使用mysql_fetch_row()而不是mysql_fetch_assoc()并将它们称为$ row [0]和$ row [3]。

答案 4 :(得分:1)

您可以将查询更改为:

SELECT
a.id as a_id,
a.Title,
a.Category,
c.id as c_id,
c.cateName FROM ads_list
AS a LEFT JOIN ads_cate
AS c ON c.id=a.Category WHERE a.Category = $CatID

这样,列名中没有歧义,您可以将其作为$ row ['a_id']或$ row ['c_id']

访问

答案 5 :(得分:1)

你不能从查询中删除c.id吗?如果在查询中需要它,则在SELECT语句中不需要它:

$sql = "SELECT a.id, a.Title, a.Category, c.cateName 
FROM ads_list AS a 
LEFT JOIN ads_cate AS c ON c.id=a.Category 
WHERE a.Category = $CatID"; 

$result = mysql_query($sql) or die(mysql_error());

while ($row = mysql_fetch_assoc($result)) { echo $row['id'] // equals c.id }

如果您需要它,您还可以使用PDO和值绑定。我不建议使用mysql_ *函数。 PDO更好更容易阅读:

  $query = $pdo->query('SELECT a.id, a.Title, a.Category, c.id, c.cateName 
                               FROM ads_list AS a 
                               LEFT JOIN ads_cate AS c ON c.id=a.Category 
                               WHERE a.Category = $CatID');

  $query->bindColumn(1, $id_a); //numerical index goes from 1
  $query->bindColumn(4, $id_b);
  $query->bindColumn('Title', $title); //you can also index using column name if it's possible

  while ($query->fetch(PDO::FETCH_BOUND)) //fetch returns true if there are any records to fetch
  {
    echo $id_a;
    echo $id_b;
    echo $title;
  }

此解决方案(和mysql_fetch_row)的缺点是查询中的任何更改都可能导致索引更改。即使现在不是问题,相信我 - 我已经看到了一个包含30个返回列并且应用了mysql_fetch_row的查询。这是一场噩梦。无法找出数据库中的哪一列由某个变量表示。