MySQL SELECT w/使用 php 的两个 AS id 字段名称,同时 mysql_fetch_array() 来唯一标识它们
我正在运行一个 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 。
我的问题是如何在 while() 循环中唯一获取 a.id 和 c.id 的值?
I am running a SELECT query and it has a.id and c.id like so:
$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 }
But $row['id'] is the last id called in the query and evaluates to c.id. I need to get a.id in my while loop.
My question is how do I get the value of a.id and c.id in my while() loop uniquely?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
为
c.id
列指定别名。试试这个:
Give an alias to the
c.id
column.Try this:
玩得开心
Have fun
您有两个选择:
1- 为每个 id 指定一个别名:
并将它们命名为 $row[ 'aid' ] 和 $row[ 'cid' ]。
2-使用 mysql_fetch_row() 而不是 mysql_fetch_assoc() 并将它们寻址为 $row[0] 和 $row[3]。
You have two options:
1- give each id an alias:
and address them as $row[ 'aid' ] and $row[ 'cid' ].
2- use mysql_fetch_row() instead of mysql_fetch_assoc() and address them as $row[0] and $row[3].
您可以将查询更改为类似以下内容:
这样列名称中就没有歧义,您可以将其作为 $row['a_id'] 或 $row['c_id'] 访问
you can change your query to something like:
that way there is no ambiguity in column names and you can access it as $row['a_id'] or $row['c_id']
你不能从查询中删除 c.id 吗?如果您在查询中需要它,则在 SELECT 语句中不需要它:
如果您需要它,您也可以使用 PDO 和值绑定。我不建议使用 mysql_* 函数。 PDO 更好、更容易阅读:
该解决方案(和 mysql_fetch_row)的缺点是查询中的任何更改都可能导致索引更改。即使现在这不是问题,请相信我 - 我已经看到一个包含 30 个返回列并应用了 mysql_fetch_row 的查询。这是一场噩梦。无法找出数据库中的哪一列由某个变量表示。
Can't you just remove c.id from query? You don't need that within SELECT statement if you need it in your query:
If you need it though, you can also use PDO and value binding. I do not recommend using mysql_* functions. PDO is just better and easier to read:
Downside of this solution (and mysql_fetch_row) is that any change within the query can result in change of indexes. And even if now it's not the problem, believe me - I've seen a query with 30 returned columns and mysql_fetch_row applied. It was a nightmare. Impossible to find out which column in database is represented by certain variable.