php - 定义哪个 ID 应该保留在 JOIN 表查询中

标签 php mysql

您好,我正在使用以下 SELECT

"SELECT 
   P.id
  ,P.price
  ,P.contract
  ,P.property_type


  ,CT.id
  ,CT.english_text
  ,PT.id
  ,PT.english
  ,C.cityname
  ,S.sectorname
  ,S.id


FROM properties P
JOIN contract CT
  ON CT.id = P.contract
JOIN property_type PT
  ON PT.id = P.property_type
JOIN city C
  ON C.id = P.city
JOIN sector S
  ON S.id = P.sector WHERE 1"

在最终结果中我总是有 id=2,我认为它是来自 S.id 的 id,因为它是最后一个。

如何进入此查询的 foreach 循环以在 $row['id'] 中显示 P.id

现在每个结果总是 $row['2']

最佳答案

您有多个名称相同的列,这会混淆 php。使用别名给它们不同的名字:

SELECT P.id as p_id, P.price, P.contract, P.property_type,
       CT.id as c_id, CT.english_text,
       PT.id as pt_id, PT.english
       C.cityname,
       S.sectorname, S.id as s_id
. . .

这会从结果集中删除所有 id。你想要的是 s_id

关于php - 定义哪个 ID 应该保留在 JOIN 表查询中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31910802/

相关文章:

php - PHP 中有从数组中提取 'column' 的函数吗?

php - "Fatal error: Cannot redeclare class"...但是类没有声明

php - 视频上传脚本不起作用

php - 删除已连接的表

php - MAMP:从 5.5 升级到 5.7 后无法启动 MySQL

php - 如何在 session 过期后自动更新数据库而不刷新我的页面

MySQL触发器插入之前

mysql - 如何在 codeigniter 中使用子句 where 和带有 2 个参数的组

search - 如何根据搜索词匹配的数量对结果进行排序?

php - 查找每行的两个值之间的差异,其中 "number"列值相同