MySQL中的JSON数组和子查询问题

huangapple go评论105阅读模式
英文:

MySQL on JSON array and subquery issues

问题

你可以使用以下SQL查询来获取与table_b中的ID对应的table_a数据:

  1. select * from table_a where id in (select json_extract(table_a_ids, '$') from table_b where id = 1);

请注意,这个查询假定你想获取table_b中ID为1的记录所关联的table_a数据。

英文:

Q: At present, I have the ID of table_b. How can I query the data corresponding to table_a?

table_a
id value
1 a1
2 a2
3 a3
table_b
id table_a_ids
1 [1, 2]
2 [2, 3]

It's not effective

  1. select * from table_a where id in (select json_extract(batch_bill_ids, '$') from table_b where id = 1);

答案1

得分: 1

  1. SELECT *
  2. FROM table_a
  3. WHERE EXISTS (
  4. SELECT NULL
  5. FROM table_b
  6. WHERE JSON_CONTAINS(table_b.table_a_ids, CAST(table_a.id AS JSON))
  7. );
英文:

Test this:

  1. SELECT *
  2. FROM table_a
  3. WHERE EXISTS (
  4. SELECT NULL
  5. FROM table_b
  6. WHERE JSON_CONTAINS(table_b.table_a_ids, CAST(table_a.id AS JSON))
  7. );
  8. </details>
  9. # 答案2
  10. **得分**: 1
  11. 可以使用 [member of][1] 运算符进行连接,如下所示:
  12. ```sql
  13. select a.id, a.value
  14. from table_a a join table_b b
  15. on a.id member of (b.table_a_ids)
  16. where b.id = 1

demo

英文:

You may do a join using the member of operator as the following:

  1. select a.id, a.value
  2. from table_a a join table_b b
  3. on a.id member of (b.table_a_ids)
  4. where b.id = 1

demo

huangapple
  • 本文由 发表于 2023年6月8日 16:45:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76430106.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定