Astrid
Astrid

Reputation: 1312

MYSQL PHP add table values as rows

I am trying to join 2 MySQL tables, but I can't manage to help myself using the examples online.

The table dat_eb_field_values countains 3 rows: registrant_id, field_id and field_value.

My second table: dat_eb_registrants contains normal rows such as user_id, first_name, last_name ect.

I am trying to get those 2 tables together so that the row: field_value can be used just like the other values from dat_eb_registrants.

Currently I am using the following method, but since the query's are not connected, I can't sort the output on field_value from the table dat_eb_field_values.

$result = mysql_query("SELECT user_id,first_name,last_name,email FROM `dat_eb_registrants`") 
while ($row = mysql_fetch_row($result)) {

    $result1 = mysql_query("SELECT field_value FROM field_values WHERE (field_id = 53) AND (user_id = $row[0])"); $r1 = mysql_fetch_row($result1); echo $r1[0];
    echo $row[2];
    $result2 = mysql_query("SELECT field_value FROM dat_eb_field_values WHERE (field_id = 54) AND (user_id = $row[0])"); $r2 = mysql_fetch_row($result2); echo $r2[0];
}

end so on....

Upvotes: 0

Views: 129

Answers (5)

Rob Forrest
Rob Forrest

Reputation: 7450

As everyone has said, the INNER JOIN is undoubtedly what you're after and its looking like a double join.

To speed up whatever result you go for make sure that you index the columns upon which you are joining. This can change a 30sec query into a .3sec one.

Upvotes: 0

burmat
burmat

Reputation: 2548

Maybe just use a join? Try the following query:

SELECT users.user_id, users.user_name, users.user_email, field_values.field_value 
FROM users LEFT JOIN field_values ON users.user_id=field_values.user_id

You can also append a WHERE clause on the back of that too, such as:

WHERE field_values.field_id='53'

If you need some more explainations on JOIN, refer to this great answer: https://stackoverflow.com/a/5874895/586859

When you run this, you can just loop through your results as normal, but all of your values should be contained in one spot.

Upvotes: 1

fd8s0
fd8s0

Reputation: 1927

I think what you want is something like this

select u.*, v1.field_value as field_53, v2.field_value as field_54 
from users u 
join values as v1 on v1.user_id = u.user_id AND v1.field_id = 53 
join values as v2 on v2.user_id = u.user_id AND v2.field_id = 54;

Though it's a double join and it's quite horrid I believe...

Upvotes: 0

Samuel Cook
Samuel Cook

Reputation: 16828

JOIN can help you here:

SELECT u.user_id,u.user_name,u.user_email,f.field_value FROM users u LEFT JOIN field_values f ON f.field_id=u.user_id

This is assuming that field_id matches user_id

Upvotes: 0

ethrbunny
ethrbunny

Reputation: 10479

How about:

select * from users join field_values using( user_id ) where field_id in (53,54);

Upvotes: 0

Related Questions