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

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

MySQL on JSON array and subquery issues

问题

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

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

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

答案1

得分: 1

SELECT *
FROM table_a
WHERE EXISTS (
   SELECT NULL
   FROM table_b 
   WHERE JSON_CONTAINS(table_b.table_a_ids, CAST(table_a.id AS JSON))
   );
英文:

Test this:

SELECT *
FROM table_a
WHERE EXISTS (
   SELECT NULL
   FROM table_b 
   WHERE JSON_CONTAINS(table_b.table_a_ids, CAST(table_a.id AS JSON))
   );

</details>



# 答案2
**得分**: 1

可以使用 [member of][1] 运算符进行连接,如下所示:

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

demo

英文:

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

select a.id, a.value
from table_a a join table_b b
on a.id member of (b.table_a_ids)
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:

确定