且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 where 子句从两个表中进行选择查询.

更新时间:2023-02-14 15:48:31

你可以UNION两个表

SELECT  email, code, name
FROM
(
    SELECT email, tutor_code as code, tutor_name as Name FROM tutor
    UNION ALL
    SELECT email, institute_code  as code, institute_name as Name FROM institute
) sub
WHERE   code = $code AND
        name = '$name'

SELECT  s.*, c.*
FROM
        (
            SELECT  contact_ID, 
                    tutor_code as code, 
                    tutor_name as Name,
                    'TUTOR' sourceTbl
            FROM    tutor
            WHERE   tutor_code = $code AND
                    tutor_name = '$name'
            UNION ALL
            SELECT  contact_ID,
                    institute_code  as code, 
                    institute_name as Name,
                    'INSTITUTE' sourceTbl
            FROM    institute
            WHERE   institute_code = $code AND
                    institute_name = '$name'
        ) s
        INNER JOIN contact c
            ON s.contact_ID = c.contact_ID

请记住,由于在 UNION 中指定了 ALL,如果两个记录都存在于两个表中,它将返回重复的记录.如果您只想获取唯一记录,请删除 ALL.

keep it mind that it will return duplicate record if both records exists on both table because of specifying ALL in the UNION. If you want to get only unique records, remove ALL.