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

Discussion Overview

The discussion revolves around finding common elements between two lists retrieved from SQL queries. Participants explore different methods to achieve this, including SQL queries and PHP nested loops, focusing on efficiency and effectiveness.

Discussion Character

  • Technical explanation
  • Debate/contested

Main Points Raised

  • One participant presents a scenario where two SQL queries return lists of names, seeking the most efficient method to find common elements.
  • Another participant suggests using the SQL INTERSECT operator to find common names directly from the two queries.
  • A different participant proposes using an INNER JOIN to achieve the same result, specifying conditions for both the type and name.
  • A later reply mentions that the join method works well with MySQL, indicating a positive initial experience but noting the need for comparative statistics.

Areas of Agreement / Disagreement

Participants present multiple approaches to the problem, with no consensus on the most efficient method. The discussion includes differing opinions on using SQL INTERSECT versus INNER JOIN.

Contextual Notes

Some participants do not specify the database management system being used, which may affect the applicability of certain methods. There is also a lack of detailed performance metrics to compare the suggested approaches.

Who May Find This Useful

Readers interested in SQL query optimization, database management, and programming efficiency may find the discussion relevant.

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.
 

Similar threads

Replies
7
Views
2K
  • · Replies 7 ·
Replies
7
Views
5K
  • · 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
7K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 2 ·
Replies
2
Views
471
Replies
5
Views
14K