Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

168
Visualizações
Combine SQL queries for efficiancy

I have the following queries.

SELECT DISTINCT goid, backid FROM trip WHERE userID = ?
SELECT goid, count(goid) FROM trip WHERE userID = ? GROUP by goid
SELECT backid , count(backid ) FROM trip WHERE userID = ? GROUP by backid 

I am wondering if there is any way to maybe merge the 3 queries, or at least the last 2 queries into 1. Also if only the last 2 can be merged how can I essentially add the the results of the 2 to 1 colum eg 1011 => 20 as column backid and goid may have the same id and in this case the count should be added

Picture shows example output of 2nd query The 3rd query is exactly the same but from a different column

Minimal example:

create table trip (
    goid varchar(255),
    backid varchar(255)
);

insert into trip (goid, backid) values ('EGLL', 'EGLL');
insert into trip (goid, backid) values ('VABB', 'VABB');
insert into trip (goid, backid) values ('KSEE', 'BHAS');
insert into trip (goid, backid) values ('EGNM', 'YSSY');
insert into trip (goid, backid) values ('OBMD', 'KSBD');
insert into trip (goid, backid) values ('EGLL', 'VABB');


SELECT goid, count(goid) FROM trip  GROUP by goid;
SELECT backid , count(backid ) FROM trip GROUP by backid;
SELECT DISTINCT goid, backid FROM trip

https://phpize.online/?phpses=ba9b2b20aab7889cbe83cb65527594e3&sqlses=9b7df2746f3828b9f34ae2ad42050b93&php_version=php8&sql_version=mysql80

In the example I removed the userid as its not relevant. But main aim is for the 1st and 2nd select queries in the example to be merged into one and the out put 2 be merged, ie if EGLL in goid and backid then they are essentialy 1 key and the count added together. Over all the 2 count queries should look something similar to the picture combined

enter image description here

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Use UNION ALL to combine goids and backids and then aggregate:

SELECT id, COUNT(*)
FROM (
  SELECT goid AS id FROM trip
  UNION ALL
  SELECT backid FROM trip
) t
GROUP BY id;

See the demo.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda