使用多个表进行查询

时间:2012-11-27 07:17:46

标签: mysql sql select union

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 个答案:

答案 0 :(得分: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";

答案 1 :(得分: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

给我一​​点时间,从手机切换到电脑......阅读文章的同时;)

抱歉,花了一点时间。我看到你已经找到了一个解决方案,所以我不打算深入挖掘这个更长的

答案 2 :(得分: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

答案 3 :(得分:0)

尝试加入。

SELECT table1.field, table2.field, table3.field 
FROM table1 
JOIN table2 ON table1columnToMatch = table2columnToMatch
JOIN table3 ON table2columnToMatch = table3columnToMatch
WHERE tableWithKeyword.keyword = $keyword