【问题标题】:select data using 'IN' in MySQL using joins on multiple tables [duplicate]使用多个表上的连接在 MySQL 中使用“IN”选择数据 [重复]
【发布时间】:2021-11-26 14:16:59
【问题描述】:

有很多这样的问题,但没有帮助我我有多个包含不同数据的表。 有一个机构表,其中包含多个机构

机构

id name
1 A
2 B

我在课程表中使用了机构的 ID

课程

id course inst_id
1 A 1,2
2 B 1

现在我想根据 courses.inst_id 选择机构名称,当 course.id = 2 时它返回 B 很好,但当 id = 1 时它只返回一个机构名称但 inst_id 包含在 1,2 上,因此它应该返回两个值 A 和 B 有什么办法吗?

这是我的尝试

$match = '1,2';
    $stmt = $db->prepare("SELECT courses.*, teachers.name,i.name as institute FROM courses 
    JOIN teachers ON teachers.id =  courses.teacher_id JOIN institutes i WHERE i.id IN 
    ($match) AND courses.id = :id ");
    $stmt->execute([':id' => $id]);
    return $stmt->fetch(PDO::FETCH_ASSOC);

【问题讨论】:

  • 您不要在 SQL 的任何地方使用 inst_id
  • 您实际上是否将值存储为逗号分隔值?
  • $match 应该已经被参数化了。
  • 如果你有可能改变你的表格设计,并且不要将值存储为逗号分隔
  • 是的,我用逗号分隔存储数据

标签: php mysql join


【解决方案1】:

inst_id保存为'1','2'等字符串

检查这个查询

SELECT courses.*, teachers.name,i.name as institute 
FROM courses 
JOIN teachers ON teachers.id =  courses.teacher_id JOIN institutes i WHERE i.id IN 
(SELECT data_set.inst_id FROM (select inst_id from courses) AS data_set) AND courses.id = :id 

根据需要对查询进行必要的更改。

【讨论】:

  • 你能解释一下这行(SELECT data_set.inst_id FROM (select inst_id from table_a) AS data_set)吗?
  • 这将从in的课程中返回inst_id
  • select inst_id from courses 不会自己做吗?另外,您在该代码中的哪个位置将其与用户提供的值进行比较?
  • @Dharman 是的,你是对的。需要更新查询。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-06
  • 2011-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多