[英]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. 我正在尝试加入2个MySQL表,但是我无法在线上使用示例帮助自己。
The table dat_eb_field_values
countains 3 rows: registrant_id, field_id and field_value. 表dat_eb_field_values
3行:registrant_id,field_id和field_value。
My second table: dat_eb_registrants
contains normal rows such as user_id, first_name, last_name ect. 我的第二个表: dat_eb_registrants
包含普通行,例如user_id,first_name,last_name等。
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
. 我正在尝试将这两个表放在一起,以便可以像dat_eb_registrants
的其他值一样使用row: 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
. 当前,我正在使用以下方法,但是由于未连接查询,因此无法对表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.... 这样结束....
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子句,例如:
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 如果您需要有关JOIN的更多说明,请参考以下出色答案: 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. 运行此命令时,您可以照常循环浏览结果,但是所有值都应包含在一个位置。
怎么样:
select * from users join field_values using( user_id ) where field_id in (53,54);
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... 我相信这虽然是两次聚会,而且非常恐怖。
As everyone has said, the INNER JOIN
is undoubtedly what you're after and its looking like a double join. 就像每个人都说过的那样, INNER JOIN
无疑是您所追求的,并且看起来像是双重INNER 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. 这可以将30秒的查询更改为0.3秒的查询。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.