1
SELECT keyword 
FROM
(
    SELECT tutor_Name AS keyword FROM t
    UNION
    SELECT subject_name AS keyword FROM s
    UNION
    SELECT institute_name AS keyword FROM i
) s
WHERE keyword LIKE '%$queryString%' 
LIMIT 10

此查询根据关键字显示包含主题、导师姓名、城市的列表。现在我需要用更多的值修改这个查询。例如,列表中有一个导师姓名,我想显示他/她当前的城市、他/她的个人资料图像等。所以我需要从我的城市表、地址表、tutorImages 表中获取这些值。所以任何人都可以帮我做这个查询?

4

4 回答 4

2

试试这个它会工作:

$q = "SELECT keyword, col, city_name, image_name, tutor_code 
            FROM (
                SELECT tutor_name AS keyword, 'Tutors' AS col, IFNULL(c1.city_name, '') city_name, IFNULL(ti.image_name, '') image_name, tutor_code FROM tutors AS t
                LEFT JOIN address a ON t.address_id = a.address_id
                LEFT JOIN city c1 ON a.city_id = c1.city_id 
                LEFT JOIN tutor_images ti ON t.tutor_id = ti.tutor_id and ti.image_type = 'profile'
                UNION
                SELECT subjects AS keyword, 'Subject' AS col, '' city_name, '' image_name, '' tutor_code FROM subject
                UNION
                SELECT city_name AS keyword, 'City' AS col, '' city_name, '' image_name, '' tutor_code FROM city
                UNION
                SELECT institute_name AS keyword, 'Institute' AS col, '' city_name, '' image_name, '' tutor_code FROM institutes
            ) s
          WHERE keyword LIKE '%$queryString%' 
          LIMIT 10";
于 2012-11-27T13:33:40.167 回答
1

第一个查询的问题是,您获取未过滤的每个表的所有结果,合并它们,区分它们,然后过滤结果。这在查询时间和资源方面是非常无效的。

您在这里需要的是 JOIN。要了解连接的工作原理,请阅读此内容

http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html

和这个

http://dev.mysql.com/doc/refman/5.5/en/join.html

为了让您了解查询的外观:重构旧的

SELECT

给我一点时间,从手机切换到电脑。一边阅读文章;)

抱歉,时间有点长。我看到你同时找到了一个解决方案,所以我不会费心深入研究这个

于 2012-11-27T07:36:35.473 回答
1

尝试这个:

SELECT keyword, city_name, image_name
FROM (
SELECT tname AS keyword, IFNULL(c1.city_name, '') city_name, IFNULL(ti.image_name, '') image_name FROM t 
LEFT JOIN address a ON t.address_id = a.address_id
LEFT JOIN city c1 ON a.city_id = c1.city_id 
LEFT JOIN tutorImages ti ON t.tutor_id = t1.tutor_id 
UNION
SELECT sname AS keyword, '' city_name, '' image_name FROM sub
UNION
SELECT cname AS keyword, '' city_name, '' image_name FROM c
UNION
SELECT iname AS keyword, '' city_name, '' image_name FROM i ) s
WHERE keyword LIKE '%$queryString%' 
LIMIT 10
于 2012-11-27T07:36:44.037 回答
0

尝试加入。

SELECT table1.field, table2.field, table3.field 
FROM table1 
JOIN table2 ON table1columnToMatch = table2columnToMatch
JOIN table3 ON table2columnToMatch = table3columnToMatch
WHERE tableWithKeyword.keyword = $keyword
于 2012-11-27T07:30:17.403 回答