简体   繁体   English

如何通过一个查询使用PHP获取MySQL字段?

[英]How can I get the MySQL fields using PHP with one query?

Basically, I have two tables (copied from WordPress): users and user_meta. 基本上,我有两个表(从WordPress复制):users和user_meta。 User_meta has 4 columns: meta_id, user_id, meta_key, meta_value. User_meta有4列:meta_id,user_id,meta_key,meta_value。 Each row has an unique meta_id, but multiple rows can have the same user_id. 每行具有唯一的meta_id,但多行可以具有相同的user_id。 I want to get everything from users (users.*) and all of the meta_values associated with the user with as few queries as possible. 我想从用户(users。*)以及与用户关联的所有meta_values中获取所有信息,并尽可能减少查询。 Also, I want to be able to use mysql_fetch_object on the returned resource. 另外,我希望能够在返回的资源上使用mysql_fetch_object。

Here's what I'm using right now: 这是我现在正在使用的:

SELECT *, (SELECT role FROM usermeta WHERE user_id=ID) as role FROM users WHERE ID=1

EDIT: I don't think I was clear that there are multiple usermeta rows with the same user_id and meta_key. 编辑:我不认为我很清楚,有多个usermeta行具有相同的user_id和meta_key。

what about join ? 那加入呢?

SELECT * FROM users 
JOIN user_meta ON users.user_id=user_meta.user_id 
WHERE users.user_id=1

Fetch Object: 获取对象:

$q = mysql_query('select * from users join user_meta on users.user_id=user_meta.user_id  where users.user_id=1');
while($r = mysql_fetch_object($q))
{
   echo $r->user_id;
   echo ...
   echo ...

}

Try: 尝试:

select u.* from users u join user_meta um on (u.user_id=um.user_id) where u.id = 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 php mysql 中使用“AND”查询获得多于一行 - How can I get more then one row with “AND” query in php mysql 如何通过一个查询或PHP在MySQL中获取所需的数据? - How to get the data I want in MySQL in one query or in PHP? 我如何用php创建比此更好的mysql查询 - How can I create a better mysql query with php than this one 如何一次动态查询一次使用php在mysql中插入多条记录? - How can I insert multiple records in mysql using php at once with one query dynamicaly? 搜索引擎使用php和mysql,六个字段组成一个查询? - Search engine using php and mysql, six fields into one query? 如何编写一个查询来获取mysql中的计数 - how can i write as one query to get count in mysql 使用php访问mysql,如何获得仅是数字的查询结果? - Using php to access mysql, how can I get the query result which is only a number? 使用PHP Mysql,如何从sql查询中的多个OR条件中满足哪个条件? - Using PHP Mysql how can I get which condition satisfied from multiple OR condition in a sql query? 如何使用php从MySQL查询中获取索引值? - How can i get the index value from the MySQL query with php? 我的php代码中有一个mysql查询,该查询被剪切并粘贴在两个地方。 我如何才能将它放在一个地方? - I have a mysql query in my php code that is cut and pasted in two places. How can I get it to be in one place?
相关标签
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM