0

I have a very large dataset, and I am trying to do a LEFT outer join, but keep losing some of my left table rows because of where I place my WHERE command, similar to the problem and solution here.

Example 1

SELECT *
FROM table1
LEFT JOIN table2 
    USING (IDvar)
    WHERE table2.var IN(val1, val2,..., val100);

This only selects the rows in the first/left table (table1) that have a matching row in the second/right table (table2). The second example is what is likely to work:

Example 2

SELECT *
FROM table1
LEFT JOIN table2 
    USING (IDvar)
    AND (table2.var = val1 OR table2.var = val2);

But, I have like 200 table2.var values that I would like to include, which are sporadic and and non-continuous (can't use syntax like table2.var >= val1).

An example of what I thought should work is to use "AND" and "IN" such as (because I have the values as a comma-separated list):

Example 3

SELECT *
FROM table1
LEFT JOIN table2 
    USING (IDvar)
    AND table2.var IN(val1, val2,..., val100);

So how can I get many many values into an AND command?

I've found a working solution, but it takes way way to long to perform.

Example 4 - Working Example but takes too long

SELECT *
FROM table1
LEFT JOIN (SELECT table2.var WHERE table2.var IN(val1, val2,..., val100)) AS t
    USING (IDvar);

Is there any way of optimising this query, it is taking way too long?

Nicolas
  • 374
  • 4
  • 18
  • you can do an "Inner join" with Services table instead of "in" condition – srp Mar 26 '18 at 04:39
  • Check my edit. An inner join would mean I would lose many of the table1 rows that don't have a matching row in table 2, which is the problem I have been having using the where command. – Nicolas Mar 26 '18 at 05:04
  • Use the third example, replacing IN with FIND_IN_SET – Strawberry Mar 26 '18 at 06:18
  • Thanks for the comment, but switching out the IN with FIND_IN_SET throws an error, and even when I modify it like in the MySQL docs. It seems to really need the WHERE clause, but that subsets my Left table (table1) and I need to have all my records in table 1, regardless if they match. I'm pretty sure I found a working solution using a subquery, but the subquery takes forever to run. – Nicolas Mar 27 '18 at 03:36

0 Answers0