Ir para conteúdo

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

halfar

inner join - clausula on num mesmo inner

Recommended Posts

No meu livro de mysql consta um exemplo de um relacionamento de tabelas, onde existem várias cláusulas ON num mesmo inner join, assim:


 

Citar

 

select * from tabela1 (inner join tabela2 on tabela1.campo1 = tabela2.campo1 and

 

on tabela1.campo2 = tabela2.campo2 or

 

on tabela1.campo3 = tabela2.campo3)


 

mas tentei este método e gerou erro de script.

 

será que isto funciona mesmo?

 

Mas até me pergunto pra que isso, sendo que posso deixar apenas um "on" e mantenho apenas os demais "and". 

 

Mas será que realmente funciona como o livro explicou??

Compartilhar este post


Link para o post
Compartilhar em outros sites

acho que está errado...

Não sei o que quer fazer e que tabelas realmente está usando (contexto) ou mesmo o que é obrigatório ou não...

 tente

select t1.* 
  from tabela1 t1
       join tabela 2 t2
         on t2.campo = t1.campo
       left join tabela3 t3
              on t3.campo = t1.campo

 

nesse caso o t1 e t2 são obrigatórios, e o t3 somente se o t3 existir.

caso tenha a mesma condição do t3, use left join também no t2

Compartilhar este post


Link para o post
Compartilhar em outros sites

@halfar, buenas.

 

O erro está em usar o ON várias vezes.

select * 
from tabela1 
(inner join tabela2 on 
tabela1.campo1 = tabela2.campo1 
and tabela1.campo2 = tabela2.campo2 
or tabela1.campo3 = tabela2.campo3)

 

Compartilhar este post


Link para o post
Compartilhar em outros sites

  • Conteúdo Similar

    • Por cesarhtc
      Boa noite, estou precisando copiar tabelas oracle, como são muitas tabelas só quero copiar somente aquelas que foram alteradas em seus registros ou estrutura no dia (diariamente).
       
      desde já agradeço.
    • Por aw10home
      Quando faço a consulta no phpMyadmim consigo o resultado esperado. Mas pelo visto não estou sabendo fazer direito em PHP. O que estou errando? Porque não consigo fazer a média (prtm) "aparecer"?
      abaixo meu código.
      <?php if (isset($_GET['$id_aluno'])){ $id_aluno = addslashes($_GET['$id_aluno']);} elseif (isset($_GET['id_aluno'])){ $id_aluno = addslashes($_GET['id_aluno']);}//addslashes evita sqlinjection else{ $id_aluno=(""); } $informacao=$con->prepare("SELECT a.id_aluno, a.nome, SUM(((b.prt*5)+(m.prt*3)+(v.prt*2))/10 ) as prtm FROM aluno a inner join avb1 b on a.id_aluno = b.id_aluno inner join avm2 m on a.id_aluno = m.id_aluno inner join avp v on a.id_aluno = v.id_aluno group by a.id_aluno, a.nome WHERE a.id_aluno = $id_usuario"); $informacao->execute(); ?> <!------------> <table class="cBolt"> <tr> <td>Avaliação</td> <td>Bim.</td> <td>Português</td> </tr> <?php while($linha=$informacao->fetch(PDO::FETCH_ASSOC)){ ?> <tr> <td>Média</td> <td>1º</td> <td><?php echo $linha['prtm'];?></td> </tr> <?php } ?> </table>  
    • Por lucianfpaula
      Galera tenha a seguinte duvida, tenho 3 tabelas onde estou trazendo os dados e preciso fazer um count em uma delas
       
      SELECT *  FROM tabela1 AS t1  INNER JOIN tabela2 AS t2 ON t1.idt1 = t2.idt2 INNER JOIN tabela3 AS t3 ON t3.idt3 = t1.idt1  
      a duvida é: quero manter o SELECT * mas também preciso de COUNT(t3.idT3)
      não sei se é possível fazer isso, mas gostaria de ter certeza antes de focar em outra solução
      desde já muito grato.
    • Por r.guerra
      Salve galera, boa tarde a todos.
      estou tendo um problema que ainda nao consegui enxergar... faço uma consulta mysql que funciona normalmente no proprio ambiente(mysql) mas ao solicitar a exibição do campo via php gera nao exibe e me tras um alerta.
       
      ****codigo php
      function monta_avaliacao($cpf){
          $query = mysqli_query($_SESSION["conector"],"SELECT c.*, a. cliente AS clientes FROM clientes AS c INNER JOIN avaliacoes AS a ON c.id = a.cliente WHERE c.cpf='$cpf'");
           $dados = mysqli_fetch_assoc($query);
          print $dados['c.cpf'];
           }
       
      *****sainda no html
      Notice: Undefined index: c.cpf in C:\xampp\htdocs\acus\inclusoes\funcoes.php on line 29
      Notice: Undefined index: a.pe in C:\xampp\htdocs\acus\inclusoes\funcoes.php on line 30
       
      tenho um arquivo com as funções, e apenas mando os parametros.
    • Por Quencyjones79
      Olá a todos, sou novo na área de multimídia. Estou a seguir a um momento um ebook sobre a criação de uma base de dados e também a criação de tabelas. Mas quando vinculei as tabelas do banco de dados, no phpmyadmin me deu alguns erros. Fiz a correspondência da chave primária (artist_id da tabela Artist) com a artist_id da tabela Prints (chave estrangeira) e assim por diante. O problema é que ele não mostra minhas relações das tabelas e me dá uma mensagem de erro. Então, alguns de vocês poderiam me ajudar, por favor, a consertar esta situação. Eu serei grato. Cumprimentos.
       
      Ps .: Abaixo envio o arquivo Sql.
       
      Atentamente,

      José Moreira
      -- phpMyAdmin SQL Dump -- version 5.0.2 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Jan 07, 2021 at 08:49 PM -- Server version: 10.4.14-MariaDB -- PHP Version: 7.2.33 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `ecommerce` -- -- -------------------------------------------------------- -- -- Table structure for table `artists` -- CREATE TABLE `artists` ( `artist_id` int(10) UNSIGNED NOT NULL, `first_name` varchar(20) DEFAULT NULL, `middle_name` varchar(20) DEFAULT NULL, `last_name` varchar(40) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4; -- -------------------------------------------------------- -- -- Table structure for table `customers` -- CREATE TABLE `customers` ( `customer_id` int(10) UNSIGNED NOT NULL, `email` varchar(60) NOT NULL, `pass` char(40) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4; -- -------------------------------------------------------- -- -- Table structure for table `orders` -- CREATE TABLE `orders` ( `order_id` int(10) UNSIGNED NOT NULL, `customer_id` int(10) UNSIGNED NOT NULL, `total` decimal(10,2) UNSIGNED NOT NULL, `order_date` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp() ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -------------------------------------------------------- -- -- Table structure for table `order_contents` -- CREATE TABLE `order_contents` ( `oc_id` int(10) UNSIGNED NOT NULL, `order_id` int(10) UNSIGNED NOT NULL, `print_id` int(10) UNSIGNED NOT NULL, `quantity` tinyint(3) UNSIGNED NOT NULL DEFAULT 1, `price` decimal(6,2) UNSIGNED NOT NULL, `ship_date` datetime DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -------------------------------------------------------- -- -- Table structure for table `prints` -- CREATE TABLE `prints` ( `print_id` int(10) UNSIGNED NOT NULL, `artist_id` int(10) UNSIGNED NOT NULL, `print_name` varchar(60) NOT NULL, `price` decimal(6,2) UNSIGNED NOT NULL, `size` varchar(60) DEFAULT NULL, `description` varchar(255) DEFAULT NULL, `image_name` varchar(60) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4; -- -- Indexes for dumped tables -- -- -- Indexes for table `artists` -- ALTER TABLE `artists` ADD PRIMARY KEY (`artist_id`), ADD UNIQUE KEY `full_name` (`last_name`,`first_name`,`middle_name`); -- -- Indexes for table `customers` -- ALTER TABLE `customers` ADD PRIMARY KEY (`customer_id`), ADD UNIQUE KEY `email` (`email`), ADD KEY `login` (`email`,`pass`); -- -- Indexes for table `orders` -- ALTER TABLE `orders` ADD PRIMARY KEY (`order_id`), ADD KEY `customer_id` (`customer_id`), ADD KEY `order_date` (`order_date`); -- -- Indexes for table `order_contents` -- ALTER TABLE `order_contents` ADD PRIMARY KEY (`oc_id`), ADD KEY `order_id` (`order_id`), ADD KEY `print_id` (`print_id`), ADD KEY `ship_date` (`ship_date`); -- -- Indexes for table `prints` -- ALTER TABLE `prints` ADD PRIMARY KEY (`print_id`), ADD KEY `artist_id` (`artist_id`), ADD KEY `print_name` (`print_name`), ADD KEY `price` (`price`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `artists` -- ALTER TABLE `artists` MODIFY `artist_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `customers` -- ALTER TABLE `customers` MODIFY `customer_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `orders` -- ALTER TABLE `orders` MODIFY `order_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `order_contents` -- ALTER TABLE `order_contents` MODIFY `oc_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `prints` -- ALTER TABLE `prints` MODIFY `print_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
       

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.