ATMathew
ATMathew

Reputation: 12866

Selecting Values From Another Table

So I have two seperate tables. In the first table, there are a bunch of ad groups which have an id. In the second table are a bunch of ads which have a column which contains the ad_group id for each ad. The ad_group_id is merely the id for the ad group from the ad group table. Therefore, I'm trying to select all ads which have an ad_group_id of 103, 104,105,107,117117,and 120.

So I tried the following query.

SELECT * FROM ads WHERE ad_group_id LIKE '%103%' OR ad_group_id LIKE '%104%'
OR ad_group_id LIKE '%105%' OR ad_group_id LIKE '%107%' OR ad_group_id LIKE '%117%' OR ad_group_id LIKE '%118%' OR ad_group_id LIKE '%120%';

So did the previous query work? YES

Was my query efficient? NO!

I am wondering how I can run the previous MySQL query in a more efficient manner.

EDIT:

AD GROUP - table 1
id    name
100   Tony
100   David
103   James
104   Ann
105   Jon
150   Sara

AD - table 2
keyword   ad_group_id
that        103
one         100
is          105
special     104
no          100
please      103

So I should end up with:

that        103
is          105
special     104
please      103

Hope that makes sense.

EDIT 2:

The following code gives the same result and is shorter, but I can't imagine doing this when there is more values I need to select.

SELECT * FROM ads WHERE ad_group_id IN (103,104,105,107,117,118,120);

Upvotes: 0

Views: 147

Answers (1)

Andrej
Andrej

Reputation: 7504

As I understand you store ad_group_id like id1,id2,id3 and so on. If yes this relation is many-to-many and more effectively to create additional table with 2 columns ad_id,ad_group_id. But it depends on amount of your data.

Upvotes: 1

Related Questions