[英]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.