我从一个表中有两个不同的查询,我想将这些查询合并到另一个列
首先查询:
select user_id,meta_value as fee
FROM magni_usermeta
WHERE meta_key LIKE 'clinic_%_fee'
ORDER BY user_id DESC
结果:
user_id fee
*********************
7 500
5 450
5 344
4 500
4 700
2 210
2 200
第二个查询:
select user_id,meta_value as clinic
FROM magni_usermeta
WHERE meta_key LIKE 'clinic_%_clinic_name'
ORDER BY user_id DESC
结果:
user_id clinic
*********************
7 99
5 90
5 99
4 99
4 92
2 91
2 90
我想要一个可以提供类似内容的查询:
user_id fee clinic
**********************************
7 500 99
5 450 90
5 344 99
4 500 99
4 700 92
2 210 91
2 200 90
我试过这个但是没有得到我想要的确切结果:
select user_id,meta_value as clinic
FROM magni_usermeta
WHERE meta_key LIKE 'clinic_%_clinic_name'
UNION select user_id,meta_value as fee
FROM magni_usermeta
WHERE meta_key LIKE 'clinic_%_fee'
ORDER BY user_id DESC
答案 0 :(得分:0)
您可以使用分组
select
A.user_id,
group_concat( case when A.tableName = 'fee' then A.meta_value end) as fee,
group_concat( case when A.tableName = 'clinic' then A.meta_value end) as clinic
from (
select user_id,meta_value as meta_value, 'fee' as tableName FROM magni_usermeta WHERE meta_key LIKE 'clinic_%_fee'
union
select user_id,meta_value as meta_value, 'clinic' as tableName FROM magni_usermeta WHERE meta_key LIKE 'clinic_%_clinic_name'
) as A
group by A.user_id
答案 1 :(得分:0)
我们需要加入自己以获得诊所名称:
SELECT um.user_id, um.meta_value AS fee, um2.meta_value AS clinic
FROM magni_usermeta um
JOIN magni_usermeta um2 ON um2.meta_key = REPLACE(um.meta_key, '_fee', '_clinic_name')
WHERE um.meta_key LIKE 'clinics_%_fee'
ORDER BY um.user_id DESC
答案 2 :(得分:0)
试试这个,
SELECT a.user_id, a.meta_value as fee, b.meta_value as clinic
FROM magni_usermeta a
JOIN magni_usermeta b
ON a.user_id = b.user_id
WHERE a.meta_key LIKE 'clinic_%_fee'
AND b.meta_key LIKE 'clinic_%_clinic_name'
ORDER BY a.user_id;
答案 3 :(得分:0)
您需要使用inner join
select a.user_id,a.meta_value as clinic, fee FROM magni_usermeta a Inner Join
magni_usermeta b
on a.user_id = b.user_id
WHERE meta_key LIKE 'clinic_%_clinic_name'
ORDER BY user_id DESC
答案 4 :(得分:0)
您可以在同一个表上尝试内部联接。我有一个postmetas的例子。示例_wp_attachment_metadata
和_wp_attached_file
是我的meta_key
值。
SELECT
m1.post_id as 'POST ID',
m1.meta_id as 'META ID',
m1.meta_value AS 'meta1',
m2.meta_value AS 'meta2'
FROM wp_postmeta m1
INNER JOIN
wp_postmeta m2
ON m1.post_id = m2.post_id
WHERE
m1.meta_key = '_wp_attachment_metadata'
AND
m2.meta_key = '_wp_attached_file'
答案 5 :(得分:0)
try this;
select a.user_id,(select b.meta_value FROM magni_usermeta b WHERE b.meta_key LIKE 'clinic_%_fee' AND b.user_id=a.user_id) as fee,(select c.meta_value FROM magni_usermeta c WHERE c.meta_key LIKE 'clinic_%_clinic_name' AND c.user_id=a.user_id) as clinic from magni_usermeta a GROUP BY a.user_id ORDER BY a.user_id DESC