0

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

是保持原样还是将查询分成两部分更好,因为 where 子句在连接表中搜索

一问

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')
4

1 回答 1

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 个查询。

于 2013-01-22T10:13:43.440 回答