我的查询中有2个select语句,一个聚合计数,以及一个结合了两个表的左连接,为我提供了一些我无法访问的信息。我知道我可以创建一个临时表作为这两个查询,然后将它们连接在一个公共行上,在这种情况下,它将是用户ID。我只是想知道是否有办法在一个查询中执行此操作。
我的查询如下:
SELECT usr, COUNT( quiz_id )
AS count
FROM edo_plugin_slickquiz_scores
WHERE usr_practice = 123456
GROUP BY usr;
给我以下
USR COUNT
6 1
7 1
我的第二个查询
SELECT a.user_id, a.meta_value, b.user_nicename
FROM edo_usermeta a LEFT JOIN edo_users b
ON a.user_id = b.id
WHERE a.meta_key = 'user_practice_role';
给我以下
User_id meta_value user_nicename
-----------------------------------
6 | 5 | richbai90
5 | 1 | hi5
8 | 0 | man
7 | 1 | testing123
由于wordpress如何设置其usermeta表,最后的WHERE子句是绝对必要的。如果你熟悉wordpress,你会明白这个表格如下所示
umeta_id user_id meta_key meta_value
--------------------------------------------------
1 | 1 | first_name | bob
2 | 1 | last_name | builder
3 | 1 | nickname | bob
所以我只想要这个表中meta_key = to user_practice_role
的值我理解的方式是最好的方式吗?
答案 0 :(得分:1)
据我所知,您根本不需要临时表,您可以在第二个查询中再使用一个连接:
SELECT a.user_id, a.meta_value, b.user_nicename, COUNT(sc.quiz_id) AS Quizes
FROM edo_usermeta a
LEFT JOIN edo_users b
ON a.user_id = b.id
LEFT JOIN edo_plugin_slickquiz_scores sc
ON sc.usr = b.id
AND sc.usr_practice = 123456
WHERE a.meta_key = 'user_practice_role'
GROUP BY a.user_id, a.meta_value, b.user_nicename;
答案 1 :(得分:0)
针对子选择的左连接?
SELECT a.user_id, a.meta_value, b.user_nicename, Sub1.QuizCount
FROM edo_usermeta a
LEFT JOIN edo_users b
ON a.user_id = b.id
LEFT JOIN
(
SELECT usr, COUNT( quiz_id ) AS QuizCount
AS count
FROM edo_plugin_slickquiz_scores
WHERE usr_practice = 123456
GROUP BY usr;
) Sub1
ON a.user_id = Sub1.usr
WHERE a.meta_key = 'user_practice_role';