doulan8054 2016-06-08 13:13
浏览 66
已采纳

如何使用PHP中数组中另一个键的值获取键搜索的所有值?

I have a table with the types of cars that I have on stock:

Table cars

idCar  |  name
-------+-------
1      |  car1
2      |  car2
3      |  car3
4      |  car4

And another table with the customers that have bought each car:

Table sales

idCar  |  idCustomer
-------+------------
2      |  cust1
2      |  cust5
3      |  cust5
3      |  cust2

and I have all the values of sales table stored in an array with PHP. It looks like this:

array(4) { 
      [0]=> array(2) { 
          ["idCar"]=> string(1) "2" 
          ["idCustomer"]=> string(5) "cust1" 
      } 
      [1]=> array(2) { 
          ["idCar"]=> string(1) "2" 
          ["idCustomer"]=> string(5) "cust5" 
      } 
      .... //Here the rest of values
}

What I am trying to do is to get all the values of a car (or cars) that have been bought by a particular customer, for example, cust5.

So, if I search on the sales array for the cars that have bought the customer cust5 it should return to me, idCar with the values 2 and 3. After I will get the values of idCar and name with MySQL with that values.

I have tried using the following sql statement:

"SELECT * FROM cars WHERE FIND_IN_SET(idCar, $salesTable)";

where $salesTable is the array that contains the full sales table but of course it does not work because I am trying to parse there an array directly, instead of the values of idCar.

I would like only to pass to the sql statement the values of idCar that match with a particular customer, in this case, with cust5.

Is there some way to get only the values of idCar required with some function of PHP giving only cust5 as parameter so I would be able to apply the sql statement that I put above?

Thanks in advance!

  • 写回答

1条回答 默认 最新

  • doujiaozhao2489 2016-06-08 13:27
    关注

    Use INNER JOIN

    SELECT c.* 
    FROM `cars`  c
    INNER JOIN sales s
    ON s.idCar = c.id
    AND s.idCustomer = 'cust5'
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀