Find Common Elements in Lists: SQL Query or PHP Nested Loops?

  • Thread starter Thread starter rdx
  • Start date Start date
  • Tags Tags
    Sql
Click For Summary
To find common elements between two lists derived from SQL queries, the most efficient methods discussed include using the INTERSECT operator and performing an INNER JOIN. The INTERSECT operator directly identifies shared items, as shown in the query "SELECT name FROM foods WHERE type='fruit' INTERSECT SELECT name FROM concepts WHERE type='color';", which effectively returns "orange." Alternatively, an INNER JOIN can be utilized, as demonstrated in the query "SELECT f.name FROM foods f INNER JOIN concepts c ON f.type = 'fruit' AND f.name = c.name AND c.type = 'color';" This method is noted to work well with MySQL, providing a straightforward solution for finding common elements. Both approaches are recognized for their efficiency in handling this type of data comparison.
rdx
Messages
50
Reaction score
0
I get a list from a query. Let's say "SELECT name FROM foods WHERE type='fruit';" returns "apple, orange, banana"

I get a list from another query, "SELECT name FROM concepts WHERE type='color';" returns "red, orange, yellow"

Now what I want is to find the common element(s) in the two lists, in this case "orange."

What is the most efficient way to do this? SQL queries or PHP nested loops, or ?

Thanks.
 
Technology news on Phys.org
Code:
SELECT name FROM foods WHERE type='fruit'
INTERSECT 
SELECT name FROM concepts WHERE type='color';
 
I would have thought of using a join:

select f.name from foods f inner join concepts c on f.type = 'fruit' and f.name = c.name and c.type = 'color';
 
verty said:
I would have thought of using a join:

It works well with MySQL. It will be a while before I have comparative stats but this certainly works easily. Thanks.
 
Learn If you want to write code for Python Machine learning, AI Statistics/data analysis Scientific research Web application servers Some microcontrollers JavaScript/Node JS/TypeScript Web sites Web application servers C# Games (Unity) Consumer applications (Windows) Business applications C++ Games (Unreal Engine) Operating systems, device drivers Microcontrollers/embedded systems Consumer applications (Linux) Some more tips: Do not learn C++ (or any other dialect of C) as a...

Similar threads

Replies
7
Views
2K
  • · Replies 7 ·
Replies
7
Views
4K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 5 ·
Replies
5
Views
5K
  • · Replies 9 ·
Replies
9
Views
1K
Replies
9
Views
3K
  • · Replies 4 ·
Replies
4
Views
6K
  • · Replies 2 ·
Replies
2
Views
1K
Replies
6
Views
1K
Replies
5
Views
14K