我有两个不同的表(wp_usermeta& my cutom table-sia_licence):
wp_usermeta表: - sia_licence表(自定义): - 我希望最终数据表是这样的: -
我们尝试使用
$data = $wpdb->get_results("SELECT * FROM wp_usermeta, sia_licence WHERE wp_usermeta.user_id = sia_user_id
AND wp_usermeta.meta_key = 'first_name'
AND wp_usermeta.meta_key = 'last_name'
AND wp_usermeta.meta_key = 'phone_number'
AND wp_usermeta.meta_key = 'email'
AND wp_usermeta.meta_key = 'address'");
但得到空白数组..
答案 0 :(得分:0)
试试这个:
SELECT * FROM wp_usermeta wu
INNER JOIN sia_licence sl ON wu.user_id = sl.sia_user_id
WHERE <you can specify your filter here>;
答案 1 :(得分:0)
sla_user_id是否引用user_id?
如果是这样你想使用像这样的JOIN ......
SELECT um.*,sl.select_licence,sl.visa_expiry,sl.licence_number,sl.sia_licence,sl.driving_licence FROM `wp_usermeta`um JOIN `sia_licence`sl ON um.`user_id`=sl.`sia_user_id`;
你也可以像这样添加一个where子句
SELECT um.*,sl.select_licence,sl.visa_expiry,sl.licence_number,sl.sia_licence,sl.driving_licence FROM `wp_usermeta`um JOIN `sia_licence`sl ON um.`user_id`=sl.`sia_user_id` WHERE um.`user_id`=101;
如果需要的话。在上面的例子中,它只返回用户ID = 101。
在这种情况下,您也可以使用SELECT *,但通常这是一个坏主意,因为如果两个表之间有任何不明确的列(具有相同名称的列),它将给您一个错误,但在您的看起来你应该没问题:
SELECT * FROM `wp_usermeta`um JOIN `sia_licence`sl ON um.`user_id`=sl.`sia_user_id`;
答案 2 :(得分:0)
您需要在wp_usermeta
上执行条件聚合,以便按user_id
转动所有属性(名字,姓氏......),然后JOIN
转换sia_licence
产生所需的输出
SELECT q.user_id, q.first_name, q.last_name, q.email, q.phone_number, q.address,
l.select_licence, l.visa_expiry, l.licence_number, l.sia_licence, l.driving_licence
FROM
(
SELECT user_id,
MAX(CASE WHEN meta_key = 'first_name' THEN meta_value END) first_name,
MAX(CASE WHEN meta_key = 'last_name' THEN meta_value END) last_name,
MAX(CASE WHEN meta_key = 'phone_number' THEN meta_value END) phone_number,
MAX(CASE WHEN meta_key = 'email' THEN meta_value END) email,
MAX(CASE WHEN meta_key = 'address' THEN meta_value END) address
FROM wp_usermeta m
WHERE EXISTS
(
SELECT *
FROM sia_licence
WHERE sia_user_id = m.user_id
)
GROUP BY user_id
) q JOIN sia_licence l
ON q.user_id = l.sia_user_id
或先加入然后合并
SELECT q.user_id,
MAX(CASE WHEN meta_key = 'first_name' THEN meta_value END) first_name,
MAX(CASE WHEN meta_key = 'last_name' THEN meta_value END) last_name,
MAX(CASE WHEN meta_key = 'phone_number' THEN meta_value END) phone_number,
MAX(CASE WHEN meta_key = 'email' THEN meta_value END) email,
MAX(CASE WHEN meta_key = 'address' THEN meta_value END) address,
MAX(select_licence) select_licence,
MAX(visa_expiry) visa_expiry,
MAX(licence_number) licence_number,
MAX(sia_licence) sia_licence,
MAX(driving_licence) driving_licence
FROM wp_usermeta q JOIN sia_licence l
ON q.user_id = l.sia_user_id
GROUP BY q.user_id