-2

我有一个 MySQL 查询,它是这样的:

select 
    *, 
    (select meta_value 
        from nord_usermeta m 
        where meta_key = 'firm' and user_id = s.user_id 
        limit 1) 
        as firm, 
    (select meta_value f
        rom nord_usermeta m 
        where meta_key = 'first_name' and user_id = s.user_id 
        limit 1) 
    as first_name, 
    (select meta_value 
        from nord_usermeta m 
        where meta_key = 'last_name' and user_id = s.user_id 
        limit 1) 
    as last_name     
    from nord_submissions s 
    order by created_at desc

现在我需要使用这样的 where 子句来缩小范围:

select 
    *, 
    (select meta_value 
        from nord_usermeta m 
        where meta_key = 'firm' and user_id = s.user_id 
        limit 1) 
        as firm, 
    (select meta_value 
        from nord_usermeta m 
        where meta_key = 'first_name' and user_id = s.user_id 
        limit 1) 
    as first_name, 
    (select meta_value 
        from nord_usermeta m 
        where meta_key = 'last_name' and user_id = s.user_id 
        limit 1) 
    as last_name 

    from nord_submissions s 
    where firm like '%DG%' 
    order by created_at desc

问题显然出在我使用子查询的方式上,但我找不到在 where 子句中引用它的方法。
请帮忙。

4

2 回答 2

3

为什么要这么久...尝试使用 SELF JOIN(在查询中加入相同的表)..见下文(未测试)

 SELECT ns.*,
        um1.meta_value AS firmName,
        um2.meta_value AS firstName,
        um3.meta_value AS lastName
 FROM nord_submission ns
 INNER JOIN nord_usermeta um1 USING(id) AND meta_key = 'firm'
 INNER JOIN nord_usermeta um2 USING(id) AND meta_key = 'first_name'
 INNER JOIN nord_usermeta um3 USING(id) AND meta_key = 'last_name'
 WHERE um1.meta_value LIKE '%DG%'
 ORDER BY ns.created_at

注意:如果两个表有不同的列名,你可以互相引用,那么你可以 USING(id)ns.user_id=um1.user_id等替换

于 2013-03-15T10:06:36.333 回答
1

如果您要使用键而不是列,则必须让应用程序对其进行排序。使用如此多的子查询,您会看到性能下降。

SELECT *
FROM nord_submissions 
 INNER JOIN nord_usermeta 
 USING (user_id)
WHERE (meta_key='last_name' or meta_key='first_name' or (meta_key='firm' and meta_value LIKE '%DG%') )
ORDER BY created_at desc
于 2013-03-15T10:17:18.947 回答