SQL多子查询

时间:2015-11-04 18:39:57

标签: mysql sql

我目前正在尝试在两个子查询中找到具有相同ID的所有条目,并显示第一个表。我在使用别名时遇到了问题。

function validateField(){
var wsrgx = /\s/g;
var chrgx = /\W/g;
var fnamestring = document.getElementById("fname").value;
var lnamestring = document.getElementById("lname").value;
var result;
if (result = fnamestring.match(wsrgx)){
       console.log ("There is a whitespace character in the First Name field \nSource: " + fnamestring)
       return false;
       }
if (result = fnamestring.match(chrgx)){
       console.log ("There is a non-word character in the First Name field: \nSource: " + fnamestring);
       return false;
       }
if (result = lnamestring.match(wsrgx)){
       console.log ("There is a whitespace character in the Last Name field \nSource: " + lnamestring)
       return false;
       }
if (result = lnamestring.match(chrgx)){
       console.log ("There is a non-word character in the Last Name field \nSource: " + lnamestring)
       return false;
       }
}

我现在要针对第二个表的'PersonID'检查第一个表的'ID',并返回ID和PersonID匹配的第一个表中的行。

3 个答案:

答案 0 :(得分:0)

使用Exists执行此操作

SELECT * 
FROM   persontable p 
WHERE  id IN (SELECT id 
              FROM   workertable) 
       AND firstname LIKE 'O%' 
       AND EXISTS (SELECT 1 
                   FROM   ownstable o 
                   WHERE  phonenumberid IN (SELECT id 
                                            FROM   phonenumbertable 
                                            WHERE  home <> '' 
                                                   AND ` work ` <> '' 
                                                   AND cell <> '') 
                          AND p.id = o.personid); 

如果可能的话,将所有IN中的Exists转换为sub-queries可能效率不高

答案 1 :(得分:0)

It sounds like you can just do a simple join for this:

SELECT p.*
FROM personTable p
JOIN ownsTable o ON o.id = p.id AND p.firstName LIKE 'O%' AND o.home <> '' AND o.work <> '' AND o.cell <> '';

This will select all columns from the first table as long as the id exists in the second table, and the matching rows meet the given requirements.

答案 2 :(得分:0)

这应该适合你:)

SELECT * FROM
  (SELECT * FROM personTable
    WHERE ID IN (SELECT ID FROM workerTable) 
      AND firstName LIKE 'O%')T1 
    JOIN
  (SELECT * FROM ownsTable
    WHERE PhoneNumberID IN
      ( SELECT ID FROM phonenumberTable WHERE Home <>'' AND `Work` <>'' AND Cell <>'')) T2 
   ON (T1.ID = T2.PersonId);