Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

158
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!