Py学习  »  DATABASE

JSON字段类型的MySQL连接查询

Wayne • 6 年前 • 525 次点击  

在client_profiles表中,areas字段看起来像[ 1 ]或[2]或[1,3]等

分类将是[ 1个 ]或[2]或[1,3]等

客户端配置文件必须至少有一个区域和至少一个类别。

比如说我有100个客户档案。每一个都属于一个区域,每个区域至少有一个类别。

假设我正在做area=1,我正在查找所有类别(不管如何)以及每个类别中有多少客户机配置文件。

results example

等。

下表示例。

CREATE TABLE categories (
id INT AUTO_INCREMENT PRIMARY KEY,
category_description VARCHAR(255) NOT NULL UNIQUE,
isActive boolean NOT NULL DEFAULT true
);

CREATE TABLE areas (
id INT AUTO_INCREMENT PRIMARY KEY,
area_description VARCHAR(255) NOT NULL UNIQUE,
isActive boolean NOT NULL DEFAULT true
);

CREATE TABLE client_profiles (
id INT AUTO_INCREMENT PRIMARY KEY,
businessName VARCHAR(60) NOT NULL UNIQUE,
first_name VARCHAR(60) NOT NULL,
last_name VARCHAR(60) NOT NULL,
mob_no VARCHAR(13) NOT NULL,
email VARCHAR(30) NOT NULL,
areas JSON NOT NULL,
catarea JSON NOT NULL,
);

select id, areas 
from client_profiles
where JSON_CONTAINS(areas, '1',"$");

INSERT INTO categories (category_description, isActive) values 
('Accomodation', true),
('Automative', true),
('Adult', true),
('Arts & Crafts', true),
('Events', true),
('Financial', true),
('Garden', true),
('House & Home', true),
('IT & Technology', true),
('Kids', true),
('Legal', true),
('Medical', true),
('Pets', true),
('Pregnancy(Babies)', true),
('Property', true),
('Travel & Tourism', true),
('Transport', true),
('Wellness & Beauty', true);
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/55839
文章 [ 1 ]  |  最新文章 6 年前
MatBailie
Reply   •   1 楼
MatBailie    6 年前

我想你想要这样的东西。。。

SELECT
  c.id,
  COUNT(p.id)
FROM
  categories        c
LEFT JOIN
  client_profiles   p
    ON  JSON_CONTAINS(p.areas,      '1',                    '$')
    AND JSON_CONTAINS(p.categories, CAST(c.id AS CHAR(32)), '$')
GROUP BY
  c.id