在连接的字段中选择/搜索

时间:2013-01-22 09:41:22

标签: mysql sql

如何从联接中的字段中选择/搜索?

最好将其保留原样或将查询分成两部分,因为where子句在连接表中搜索<​​/ p>

一个查询

SELECT *
FROM user u
LEFT JOIN country c ON c.id=u.country_id
WHERE c.code='dk'

两个查询

SELECT id
FROM country
WHERE code='dk'

SELECT *
FROM user u
LEFT JOIN country c ON c.id=u.country_id
WHERE c.id='result from first query'

子查询

SELECT *
FROM user u
LEFT JOIN country c ON c.id=u.country_id
WHERE c.id IN (SELECT id FROM country WHERE code='dk')

1 个答案:

答案 0 :(得分:1)

如果要有效执行,请在where子句中包含join子句。

SELECT 
    *
FROM 
    user u
LEFT JOIN 
    country c ON c.id=u.country_id
WHERE 
    c.code='dk'

SELECT 
    *
FROM 
    user u
LEFT JOIN 
    country c ON c.id=u.country_id
    AND c.code='dk'

此代码将仅生成1个db查询,您的所有示例都将生成2个查询。