SlideShare uma empresa Scribd logo
1 de 38
Baixar para ler offline
MySQL 5.7: introdução
ao JSON Data Type
Gabriela D’Avila
@gabidavila
Fev/2017
Pesquisa sem validade
científica*
2
oi!
• Data Engineer
• tipo DBA…
• … mas diferente
• @gabidavila
• http://gabriela.io
4
O que é JSON?
• JavaScript Object Notation (desde 1999)
• Formato mais compacto que XML
• É language-independent
• Atributo-valor
6
7
Tipos de dados aceitos
• Strings
• Números
• Booleanos
• Arrays
• Objetos
8
Use UTF8
9
MySQL + JSON
Leitura Recomendada
• JSON_ARRAY()
• JSON_ARRAY_APPEND()
• JSON_ARRAY_INSERT()
• JSON_ARRAY_APPEND()
• JSON_ARRAY_INSERT()
• JSON_CONTAINS()
• JSON_CONTAINS_PATH()
• JSON_DEPTH()
• JSON_EXTRACT()
• JSON_INSERT()
• JSON_KEYS()
• JSON_LENGTH()
• JSON_MERGE()
• JSON_OBJECT()
• JSON_QUOTE()
• JSON_REMOVE()
• JSON_REPLACE()
• JSON_SEARCH()
• JSON_SET()
• JSON_TYPE()
• JSON_UNQUOTE()
• JSON_VALID()
Funções JSON
JSON Data Type
• Validação automática, documentos inválidos causam
erro
• Case sensitive (utf8mb4_bin)
• null, true, false ✅
• Null, NULL, TRUE, False 🚫
• 'a' != 'A'
• Colunas do tipo JSON não podem ter um valor DEFAULT
12
JSON Data Type
• Armazenado em formato binário
• Chaves repetidas são substituídas pela última
ocorrência
• É possível converter campos TEXT se JSON_VALID()
retorna TRUE para toda a tabela
• Conversão de TEXT para JSON é uma operação
COPY*
• Índices são possíveis devido à GENERATED COLUMNS
13
JSON Data Type
• 4 tipos de funções
• Criar JSON
• Buscar/extrair JSON
• Modificar JSON
• Retornar atributos JSON
Mais informações
14
PHP + MySQL
PHP + MySQL: encode
<?php
json_encode(object $obj);
json_encode(string $str);
json_encode('[]');
16
PHP + MySQL: decode
<?php
json_decode('[]');
/*
-> array(0) {
}
*/
json_decode('');
/*
-> NULL
*/
json_decode('{"id": 5}');
/*
-> object(stdClass)#1 (1) {
["id"]=>
int(5)
}
*/
17
Criar JSON
Para criar array
• JSON_ARRAY(val1[, val2, …])
SELECT JSON_ARRAY('laravel', 5.4, "2017-02-14");
+------------------------------------------+
| JSON_ARRAY('laravel', 5.4, "2017-02-14") |
+------------------------------------------+
| ["laravel", 5.4, "2017-02-14"] |
+------------------------------------------+
1 row in set (0.00 sec)
19
Para criar objeto
• JSON_OBJECT([key, val[, key, val] ...])
SELECT JSON_OBJECT('framework', 'laravel', 'versao', 5.4);
+----------------------------------------------------+
| JSON_OBJECT('framework', 'laravel', 'versao', 5.4) |
+----------------------------------------------------+
| {"versao": 5.4, "framework": "laravel"} |
+----------------------------------------------------+
1 row in set (0.00 sec)
20
Buscar/extrair JSON
Tabela `users`
Field Type Null Key Default Extra
id int(11) NO PRI auto_increment
id_str varchar(255) NO UNI
screen_name varchar(255) NO INDEX
response json NO
22
Extrair name, status.source
SELECT
JSON_EXTRACT(response, '$.name') AS name,
JSON_EXTRACT(response, '$.status.source') AS source
FROM users
WHERE screen_name = 'laravelsp';
*************************** 1. row ***************************
name: "Laravel SP Meetup"
source: "<a href="http://twitter.com/download/android">Twitter for Android</a>"
1 row in set (0.00 sec)
24
JSON_EXTRACT() ou ->
SELECT
response->'$.name' AS name,
response->'$.status.source' AS source
FROM users
WHERE screen_name = 'laravelsp';
*************************** 1. row ***************************
name: "Laravel SP Meetup"
source: "<a href="http://twitter.com/download/android">Twitter for Android</a>"
1 row in set (0.00 sec)
25
Modificar JSON
JSON_UNQUOTE() ≃
stripslashes()
SELECT
JSON_UNQUOTE(JSON_EXTRACT(response, '$.name')) AS name,
JSON_UNQUOTE(JSON_EXTRACT(response, '$.status.source')) AS source
FROM users
WHERE screen_name = 'laravelsp';
*************************** 1. row ***************************
name: Laravel SP Meetup
source: <a href="http://twitter.com/download/android">Twitter for Android</a>
1 row in set (0.00 sec)
27
JSON_UNQUOTE() ou ->>
SELECT
response->>'$.name' AS name,
response->>'$.status.source' AS source
FROM users
WHERE screen_name = 'laravelsp';
*************************** 1. row ***************************
name: Laravel SP Meetup
source: <a href="http://twitter.com/download/android">Twitter for Android</a>
1 row in set (0.00 sec)
28
Recapitulando
-> é igual a ->> ?
• -> é apenas usado para extração, não modifica o valor
(JSON_EXTRACT())
• ->> faz a modificação em runtime mas não altera o
JSON por si só (JSON_UNQUOTE(JSON_EXTRACT()))
30
Retornar Atributos
JSON
JSON_VALID()
SELECT
JSON_VALID("NULL"),
JSON_VALID("null"),
JSON_VALID("[]"),
JSON_VALID('{"screen_name":"laravelsp"}'),
JSON_VALID("{"screen_name":"laravelsp" }");
*************************** 1. row ***************************
JSON_VALID("NULL"): 0
JSON_VALID("null"): 1
JSON_VALID("[]"): 1
JSON_VALID('{"screen_name":"laravelsp"}'): 1
JSON_VALID("{"screen_name":"laravelsp" }"): 1
1 row in set (0.00 sec)
32
JSON_TYPE()
SELECT
JSON_TYPE(response->'$.id') AS id_type,
JSON_TYPE(response->'$.name') AS name_type,
JSON_TYPE(response->'$.status') AS status_type,
JSON_TYPE(response->'$.verified') AS verified_type
FROM users
WHERE screen_name = 'laravelsp';
*************************** 1. row ***************************
id_type: UNSIGNED INTEGER
name_type: STRING
status_type: OBJECT
verified_type: BOOLEAN
1 row in set (0.00 sec)
33
Índices
Índices
• Possíveis por meio de VIRTUAL COLUMNS ou
STORED COLUMNS
35
Dúvidas?
37
Obrigada!
• Fonte: MySQL Docs
• Twitter: @gabidavila
• Blog: http://gabriela.io
• Freenode: gabidavila #phpwomen / #phpmentoring
38

Mais conteúdo relacionado

Mais procurados

Curso mongo db com php
Curso mongo db com phpCurso mongo db com php
Curso mongo db com php
Suissa
 
Aula 01 PHP+MySQL - LabMM4
Aula 01 PHP+MySQL - LabMM4Aula 01 PHP+MySQL - LabMM4
Aula 01 PHP+MySQL - LabMM4
Carlos Santos
 

Mais procurados (20)

Introdução ao MongoDB
Introdução ao MongoDBIntrodução ao MongoDB
Introdução ao MongoDB
 
Turbinando o desenvolvimento Android com Kotlin
Turbinando o desenvolvimento Android com KotlinTurbinando o desenvolvimento Android com Kotlin
Turbinando o desenvolvimento Android com Kotlin
 
NoSQL e MongoDB - ETEC
NoSQL e MongoDB - ETECNoSQL e MongoDB - ETEC
NoSQL e MongoDB - ETEC
 
Sql proficiente
Sql proficienteSql proficiente
Sql proficiente
 
Bd sql (1)
Bd sql (1)Bd sql (1)
Bd sql (1)
 
Mobileconf dicas-android
Mobileconf dicas-androidMobileconf dicas-android
Mobileconf dicas-android
 
Elasticsearch: Motor de busca e além. Lições aprendidas criando Tu Próximo...
Elasticsearch: Motor de busca e além. Lições aprendidas criando Tu Próximo...Elasticsearch: Motor de busca e além. Lições aprendidas criando Tu Próximo...
Elasticsearch: Motor de busca e além. Lições aprendidas criando Tu Próximo...
 
MongoDB - Iniciando e Conhecendo
MongoDB - Iniciando e ConhecendoMongoDB - Iniciando e Conhecendo
MongoDB - Iniciando e Conhecendo
 
Curso mongo db com php
Curso mongo db com phpCurso mongo db com php
Curso mongo db com php
 
Apresentação Projeto Final Graduação UFF
Apresentação Projeto Final Graduação UFFApresentação Projeto Final Graduação UFF
Apresentação Projeto Final Graduação UFF
 
BigData - ElasticSearch + PHP
BigData - ElasticSearch + PHPBigData - ElasticSearch + PHP
BigData - ElasticSearch + PHP
 
Lazy Evaluation em Scala
Lazy Evaluation em ScalaLazy Evaluation em Scala
Lazy Evaluation em Scala
 
jQuery na Prática - Cauê Fajoli
jQuery na Prática - Cauê FajolijQuery na Prática - Cauê Fajoli
jQuery na Prática - Cauê Fajoli
 
Primeiros Passos Com Elasticsearch
Primeiros Passos Com ElasticsearchPrimeiros Passos Com Elasticsearch
Primeiros Passos Com Elasticsearch
 
Aula 01 PHP+MySQL - LabMM4
Aula 01 PHP+MySQL - LabMM4Aula 01 PHP+MySQL - LabMM4
Aula 01 PHP+MySQL - LabMM4
 
Big Data como Serviço: da captura à visualização de dados com alto desempenho
Big Data como Serviço: da captura à visualização de dados com alto desempenhoBig Data como Serviço: da captura à visualização de dados com alto desempenho
Big Data como Serviço: da captura à visualização de dados com alto desempenho
 
#5 CRUD no MongoDB
#5   CRUD  no MongoDB#5   CRUD  no MongoDB
#5 CRUD no MongoDB
 
Desenvolvendo para iOS com Cocoa-Touch
Desenvolvendo para iOS com Cocoa-TouchDesenvolvendo para iOS com Cocoa-Touch
Desenvolvendo para iOS com Cocoa-Touch
 
Acesso a Banco de Dados em Java usando JDBC
Acesso a Banco de Dados em Java usando JDBCAcesso a Banco de Dados em Java usando JDBC
Acesso a Banco de Dados em Java usando JDBC
 
PHPubSP Object Calisthenics aplicado ao PHP
PHPubSP Object Calisthenics aplicado ao PHPPHPubSP Object Calisthenics aplicado ao PHP
PHPubSP Object Calisthenics aplicado ao PHP
 

Destaque

Ora mysql bothGetting the best of both worlds with Oracle 11g and MySQL Enter...
Ora mysql bothGetting the best of both worlds with Oracle 11g and MySQL Enter...Ora mysql bothGetting the best of both worlds with Oracle 11g and MySQL Enter...
Ora mysql bothGetting the best of both worlds with Oracle 11g and MySQL Enter...
Ivan Zoratti
 

Destaque (20)

MySQL 8.0 Preview: What Is Coming?
MySQL 8.0 Preview: What Is Coming?MySQL 8.0 Preview: What Is Coming?
MySQL 8.0 Preview: What Is Coming?
 
MEAN Stack
MEAN StackMEAN Stack
MEAN Stack
 
Ora mysql bothGetting the best of both worlds with Oracle 11g and MySQL Enter...
Ora mysql bothGetting the best of both worlds with Oracle 11g and MySQL Enter...Ora mysql bothGetting the best of both worlds with Oracle 11g and MySQL Enter...
Ora mysql bothGetting the best of both worlds with Oracle 11g and MySQL Enter...
 
20171104 hk-py con-mysql-documentstore_v1
20171104 hk-py con-mysql-documentstore_v120171104 hk-py con-mysql-documentstore_v1
20171104 hk-py con-mysql-documentstore_v1
 
Laravel 5 and SOLID
Laravel 5 and SOLIDLaravel 5 and SOLID
Laravel 5 and SOLID
 
Mongodb
MongodbMongodb
Mongodb
 
Sharding using MySQL and PHP
Sharding using MySQL and PHPSharding using MySQL and PHP
Sharding using MySQL and PHP
 
MySQL Sharding: Tools and Best Practices for Horizontal Scaling
MySQL Sharding: Tools and Best Practices for Horizontal ScalingMySQL Sharding: Tools and Best Practices for Horizontal Scaling
MySQL Sharding: Tools and Best Practices for Horizontal Scaling
 
Strip your TEXT fields
Strip your TEXT fieldsStrip your TEXT fields
Strip your TEXT fields
 
Exploring MongoDB & Elasticsearch: Better Together
Exploring MongoDB & Elasticsearch: Better TogetherExploring MongoDB & Elasticsearch: Better Together
Exploring MongoDB & Elasticsearch: Better Together
 
Coding like a girl - DjangoCon
Coding like a girl - DjangoConCoding like a girl - DjangoCon
Coding like a girl - DjangoCon
 
Inexpensive Datamasking for MySQL with ProxySQL — Data Anonymization for Deve...
Inexpensive Datamasking for MySQL with ProxySQL — Data Anonymization for Deve...Inexpensive Datamasking for MySQL with ProxySQL — Data Anonymization for Deve...
Inexpensive Datamasking for MySQL with ProxySQL — Data Anonymization for Deve...
 
MySQL Enterprise Cloud
MySQL Enterprise Cloud MySQL Enterprise Cloud
MySQL Enterprise Cloud
 
LAMP: Desenvolvendo além do trivial
LAMP: Desenvolvendo além do trivialLAMP: Desenvolvendo além do trivial
LAMP: Desenvolvendo além do trivial
 
MySQL Cluster Whats New
MySQL Cluster Whats NewMySQL Cluster Whats New
MySQL Cluster Whats New
 
SunshinePHP 2017 - Making the most out of MySQL
SunshinePHP 2017 - Making the most out of MySQLSunshinePHP 2017 - Making the most out of MySQL
SunshinePHP 2017 - Making the most out of MySQL
 
Strip your TEXT fields - Exeter Web Feb/2016
Strip your TEXT fields - Exeter Web Feb/2016Strip your TEXT fields - Exeter Web Feb/2016
Strip your TEXT fields - Exeter Web Feb/2016
 
The MySQL Server Ecosystem in 2016
The MySQL Server Ecosystem in 2016The MySQL Server Ecosystem in 2016
The MySQL Server Ecosystem in 2016
 
[스마트스터디]MongoDB 의 역습
[스마트스터디]MongoDB 의 역습[스마트스터디]MongoDB 의 역습
[스마트스터디]MongoDB 의 역습
 
Building Scalable High Availability Systems using MySQL Fabric
Building Scalable High Availability Systems using MySQL FabricBuilding Scalable High Availability Systems using MySQL Fabric
Building Scalable High Availability Systems using MySQL Fabric
 

Semelhante a LaravelSP - MySQL 5.7: introdução ao JSON Data Type

MongoDB - Wagner Bonfiglio - Navegg
MongoDB - Wagner Bonfiglio - NaveggMongoDB - Wagner Bonfiglio - Navegg
MongoDB - Wagner Bonfiglio - Navegg
Felipe Guimarães
 
LabMM4 (T16 - 12/13) - PHP + MySQL
LabMM4 (T16 - 12/13) - PHP + MySQLLabMM4 (T16 - 12/13) - PHP + MySQL
LabMM4 (T16 - 12/13) - PHP + MySQL
Carlos Santos
 

Semelhante a LaravelSP - MySQL 5.7: introdução ao JSON Data Type (20)

NoSQL e MongoDB
NoSQL e MongoDBNoSQL e MongoDB
NoSQL e MongoDB
 
Introdução ao nosql (mini curso)
Introdução ao nosql (mini curso)Introdução ao nosql (mini curso)
Introdução ao nosql (mini curso)
 
Javaone Brazil 2012: Integrando Ext JS 4 com Java EE
Javaone Brazil 2012: Integrando Ext JS 4 com Java EEJavaone Brazil 2012: Integrando Ext JS 4 com Java EE
Javaone Brazil 2012: Integrando Ext JS 4 com Java EE
 
Documentacao automatica
Documentacao automaticaDocumentacao automatica
Documentacao automatica
 
Javascript Ilegível
Javascript IlegívelJavascript Ilegível
Javascript Ilegível
 
MySQL + JSON da casamento sim!
MySQL + JSON da casamento sim!MySQL + JSON da casamento sim!
MySQL + JSON da casamento sim!
 
Java 9, 10 e ... 11
Java 9, 10 e ... 11Java 9, 10 e ... 11
Java 9, 10 e ... 11
 
MongoDB - Wagner Bonfiglio - Navegg
MongoDB - Wagner Bonfiglio - NaveggMongoDB - Wagner Bonfiglio - Navegg
MongoDB - Wagner Bonfiglio - Navegg
 
MongoDB - Workshop Buscapé
MongoDB - Workshop BuscapéMongoDB - Workshop Buscapé
MongoDB - Workshop Buscapé
 
Minicurso mongo db
Minicurso mongo dbMinicurso mongo db
Minicurso mongo db
 
MongoDB
MongoDBMongoDB
MongoDB
 
Web App Flaws - SQL Injection
Web App Flaws - SQL InjectionWeb App Flaws - SQL Injection
Web App Flaws - SQL Injection
 
Jquery - Dicas e Truques
Jquery - Dicas e TruquesJquery - Dicas e Truques
Jquery - Dicas e Truques
 
LabMM4 (T16 - 12/13) - PHP + MySQL
LabMM4 (T16 - 12/13) - PHP + MySQLLabMM4 (T16 - 12/13) - PHP + MySQL
LabMM4 (T16 - 12/13) - PHP + MySQL
 
Oracle 11g - Fundamentos
Oracle 11g - FundamentosOracle 11g - Fundamentos
Oracle 11g - Fundamentos
 
Javascript no SAPO e libsapojs
Javascript no SAPO e libsapojsJavascript no SAPO e libsapojs
Javascript no SAPO e libsapojs
 
Minicurso de jQuery
Minicurso de jQueryMinicurso de jQuery
Minicurso de jQuery
 
Data mapping com Groovy - Part 2
Data mapping com Groovy - Part 2Data mapping com Groovy - Part 2
Data mapping com Groovy - Part 2
 
MongoDB: um banco de dados orientado a documento
MongoDB: um banco de dados orientado a documentoMongoDB: um banco de dados orientado a documento
MongoDB: um banco de dados orientado a documento
 
Apresentação sobre MVVMC
Apresentação sobre MVVMCApresentação sobre MVVMC
Apresentação sobre MVVMC
 

Mais de Gabriela Ferrara

Mais de Gabriela Ferrara (14)

GRONINGEN PHP - MySQL 8.0 , not only good, great
GRONINGEN PHP - MySQL 8.0 , not only good, greatGRONINGEN PHP - MySQL 8.0 , not only good, great
GRONINGEN PHP - MySQL 8.0 , not only good, great
 
Serverless and you @ Women Who Code London 2020
Serverless and you  @ Women Who Code London 2020Serverless and you  @ Women Who Code London 2020
Serverless and you @ Women Who Code London 2020
 
Serverless and you - where do i run my stateless code
Serverless and you  - where do i run my stateless codeServerless and you  - where do i run my stateless code
Serverless and you - where do i run my stateless code
 
PHPDay 2019 - MySQL 8, not only good, great!
PHPDay 2019 - MySQL 8, not only good, great!PHPDay 2019 - MySQL 8, not only good, great!
PHPDay 2019 - MySQL 8, not only good, great!
 
PyTexas - Machine learning APIs by Example
PyTexas - Machine learning APIs by ExamplePyTexas - Machine learning APIs by Example
PyTexas - Machine learning APIs by Example
 
MySQL 8.0: not only good, it’s GREAT! - PHP UK 2019
MySQL 8.0: not only good, it’s GREAT! - PHP UK 2019MySQL 8.0: not only good, it’s GREAT! - PHP UK 2019
MySQL 8.0: not only good, it’s GREAT! - PHP UK 2019
 
Laracon EU 2018: OMG MySQL 8.0 is out! are we there yet?
Laracon EU 2018: OMG MySQL 8.0 is out! are we there yet?Laracon EU 2018: OMG MySQL 8.0 is out! are we there yet?
Laracon EU 2018: OMG MySQL 8.0 is out! are we there yet?
 
DPC18 - Making the most out of MySQL
DPC18 - Making the most out of MySQLDPC18 - Making the most out of MySQL
DPC18 - Making the most out of MySQL
 
DPC18 - OMG MySQL 8.0 is out! are we there yet?
DPC18 - OMG MySQL 8.0 is out! are we there yet?DPC18 - OMG MySQL 8.0 is out! are we there yet?
DPC18 - OMG MySQL 8.0 is out! are we there yet?
 
php[tek] - Making the most out of MySQL
php[tek] - Making the most out of MySQLphp[tek] - Making the most out of MySQL
php[tek] - Making the most out of MySQL
 
Diving into MySQL 5.7: advanced features
Diving into MySQL 5.7: advanced featuresDiving into MySQL 5.7: advanced features
Diving into MySQL 5.7: advanced features
 
Database Wizardry for Legacy Applications
Database Wizardry for Legacy ApplicationsDatabase Wizardry for Legacy Applications
Database Wizardry for Legacy Applications
 
Coding like a girl - Youtube presentation
Coding like a girl - Youtube presentationCoding like a girl - Youtube presentation
Coding like a girl - Youtube presentation
 
Coding like a Girl
Coding like a GirlCoding like a Girl
Coding like a Girl
 

LaravelSP - MySQL 5.7: introdução ao JSON Data Type

  • 1. MySQL 5.7: introdução ao JSON Data Type Gabriela D’Avila @gabidavila Fev/2017
  • 3.
  • 4. oi! • Data Engineer • tipo DBA… • … mas diferente • @gabidavila • http://gabriela.io 4
  • 5.
  • 6. O que é JSON? • JavaScript Object Notation (desde 1999) • Formato mais compacto que XML • É language-independent • Atributo-valor 6
  • 7. 7
  • 8. Tipos de dados aceitos • Strings • Números • Booleanos • Arrays • Objetos 8
  • 10. MySQL + JSON Leitura Recomendada
  • 11. • JSON_ARRAY() • JSON_ARRAY_APPEND() • JSON_ARRAY_INSERT() • JSON_ARRAY_APPEND() • JSON_ARRAY_INSERT() • JSON_CONTAINS() • JSON_CONTAINS_PATH() • JSON_DEPTH() • JSON_EXTRACT() • JSON_INSERT() • JSON_KEYS() • JSON_LENGTH() • JSON_MERGE() • JSON_OBJECT() • JSON_QUOTE() • JSON_REMOVE() • JSON_REPLACE() • JSON_SEARCH() • JSON_SET() • JSON_TYPE() • JSON_UNQUOTE() • JSON_VALID() Funções JSON
  • 12. JSON Data Type • Validação automática, documentos inválidos causam erro • Case sensitive (utf8mb4_bin) • null, true, false ✅ • Null, NULL, TRUE, False 🚫 • 'a' != 'A' • Colunas do tipo JSON não podem ter um valor DEFAULT 12
  • 13. JSON Data Type • Armazenado em formato binário • Chaves repetidas são substituídas pela última ocorrência • É possível converter campos TEXT se JSON_VALID() retorna TRUE para toda a tabela • Conversão de TEXT para JSON é uma operação COPY* • Índices são possíveis devido à GENERATED COLUMNS 13
  • 14. JSON Data Type • 4 tipos de funções • Criar JSON • Buscar/extrair JSON • Modificar JSON • Retornar atributos JSON Mais informações 14
  • 16. PHP + MySQL: encode <?php json_encode(object $obj); json_encode(string $str); json_encode('[]'); 16
  • 17. PHP + MySQL: decode <?php json_decode('[]'); /* -> array(0) { } */ json_decode(''); /* -> NULL */ json_decode('{"id": 5}'); /* -> object(stdClass)#1 (1) { ["id"]=> int(5) } */ 17
  • 19. Para criar array • JSON_ARRAY(val1[, val2, …]) SELECT JSON_ARRAY('laravel', 5.4, "2017-02-14"); +------------------------------------------+ | JSON_ARRAY('laravel', 5.4, "2017-02-14") | +------------------------------------------+ | ["laravel", 5.4, "2017-02-14"] | +------------------------------------------+ 1 row in set (0.00 sec) 19
  • 20. Para criar objeto • JSON_OBJECT([key, val[, key, val] ...]) SELECT JSON_OBJECT('framework', 'laravel', 'versao', 5.4); +----------------------------------------------------+ | JSON_OBJECT('framework', 'laravel', 'versao', 5.4) | +----------------------------------------------------+ | {"versao": 5.4, "framework": "laravel"} | +----------------------------------------------------+ 1 row in set (0.00 sec) 20
  • 22. Tabela `users` Field Type Null Key Default Extra id int(11) NO PRI auto_increment id_str varchar(255) NO UNI screen_name varchar(255) NO INDEX response json NO 22
  • 23.
  • 24. Extrair name, status.source SELECT JSON_EXTRACT(response, '$.name') AS name, JSON_EXTRACT(response, '$.status.source') AS source FROM users WHERE screen_name = 'laravelsp'; *************************** 1. row *************************** name: "Laravel SP Meetup" source: "<a href="http://twitter.com/download/android">Twitter for Android</a>" 1 row in set (0.00 sec) 24
  • 25. JSON_EXTRACT() ou -> SELECT response->'$.name' AS name, response->'$.status.source' AS source FROM users WHERE screen_name = 'laravelsp'; *************************** 1. row *************************** name: "Laravel SP Meetup" source: "<a href="http://twitter.com/download/android">Twitter for Android</a>" 1 row in set (0.00 sec) 25
  • 27. JSON_UNQUOTE() ≃ stripslashes() SELECT JSON_UNQUOTE(JSON_EXTRACT(response, '$.name')) AS name, JSON_UNQUOTE(JSON_EXTRACT(response, '$.status.source')) AS source FROM users WHERE screen_name = 'laravelsp'; *************************** 1. row *************************** name: Laravel SP Meetup source: <a href="http://twitter.com/download/android">Twitter for Android</a> 1 row in set (0.00 sec) 27
  • 28. JSON_UNQUOTE() ou ->> SELECT response->>'$.name' AS name, response->>'$.status.source' AS source FROM users WHERE screen_name = 'laravelsp'; *************************** 1. row *************************** name: Laravel SP Meetup source: <a href="http://twitter.com/download/android">Twitter for Android</a> 1 row in set (0.00 sec) 28
  • 30. -> é igual a ->> ? • -> é apenas usado para extração, não modifica o valor (JSON_EXTRACT()) • ->> faz a modificação em runtime mas não altera o JSON por si só (JSON_UNQUOTE(JSON_EXTRACT())) 30
  • 32. JSON_VALID() SELECT JSON_VALID("NULL"), JSON_VALID("null"), JSON_VALID("[]"), JSON_VALID('{"screen_name":"laravelsp"}'), JSON_VALID("{"screen_name":"laravelsp" }"); *************************** 1. row *************************** JSON_VALID("NULL"): 0 JSON_VALID("null"): 1 JSON_VALID("[]"): 1 JSON_VALID('{"screen_name":"laravelsp"}'): 1 JSON_VALID("{"screen_name":"laravelsp" }"): 1 1 row in set (0.00 sec) 32
  • 33. JSON_TYPE() SELECT JSON_TYPE(response->'$.id') AS id_type, JSON_TYPE(response->'$.name') AS name_type, JSON_TYPE(response->'$.status') AS status_type, JSON_TYPE(response->'$.verified') AS verified_type FROM users WHERE screen_name = 'laravelsp'; *************************** 1. row *************************** id_type: UNSIGNED INTEGER name_type: STRING status_type: OBJECT verified_type: BOOLEAN 1 row in set (0.00 sec) 33
  • 35. Índices • Possíveis por meio de VIRTUAL COLUMNS ou STORED COLUMNS 35
  • 36.
  • 38. Obrigada! • Fonte: MySQL Docs • Twitter: @gabidavila • Blog: http://gabriela.io • Freenode: gabidavila #phpwomen / #phpmentoring 38