2010-06-25 84 views
2

如何針對以下情況執行SQL查詢?假設您有兩個表:table1和table2,其中table1中的每個條目可以在table2中有多個相應的條目。爲此,我想查詢的僞代碼爲:SQL查詢加入問題

for each $row in table1 
    $rows = find all rows in table2 that corresponds to $row with $row.id == table2.foreign_id 
    # $rows is an array of corresponding row in table2 
    if all rows in $rows meet some condition 
    then 
    return $row 
    else 
    continue 
    end 
end 

編輯:音符在上面的僞代碼,我只希望有它的所有關係,在符合某些條件下,不只是一些條件TABLE2在表1的行在table1中。

PS:我想在SQL中這樣做,因爲效率問題,否則我可能會遇到問題。

非常感謝。

+0

非常感謝您的信息。這個網站仍然是新的。 :) – fzhou 2010-06-25 18:28:13

回答

6

您可以使用where not exists (..)類型子句對此進行重新表達。

例如,假裝你想要的客戶,其訂單都完成的列表:

select * from customers c 
where not exists (
    select * from orders 
    where customerid=c.id 
     and status <> 'C' 
) 

所以你所要求的誰沒有未完成訂單的所有客戶 - 這是同樣的事情,所有的客戶,其訂單全部完成。

相反的:

if all rows in $rows meet some condition 

你是在說:

if NO rows in $rows DO NOT meet some condition 

編輯:正如在評論中指出,這也將返回誰沒有任何訂單的客戶。您可以在上面添加and exists (select * from orders where customerid=c.id)以排除這些行。

+0

非常感謝。這是我想要的實際查詢。我想''中的所有行都是棘手的。 – fzhou 2010-06-25 15:50:31

+1

這不會也沒有訂單返回所有客戶? – cjk 2010-06-25 15:55:53

+0

@ck true;不確定這是否會成爲問題。 – Blorgbeard 2010-06-25 15:58:57

4
select * from table1 as t1 
inner join table2 as t2 
    on t1.id == t2.foreign_id 
where -- some condition goes here 

此查詢將僅返回table1中匹配table2且匹配where子句的行。

我建議檢出SQLCourse - Interactive Online SQL Training for Beginners,因爲這實際上是一個基本的SQL查詢。

-2

一般格式爲:

SELECT * 
FROM Table1 t1 
    INNER JOIN Table2 t2 ON (t1.ID = t2.ID) 
WHERE ... 
0

我覺得這是你做了什麼,在...嵌套查詢是派生表名爲sub_query和相當於你這部分僞代碼($行=找到table2中的所有行對應於具有$ row.id == table2.foreign_id的$ row)。外部選擇讓你進一步過濾你的僞代碼的第一部分的一些條件(你的if語句)

select 
     sub_query.* 
    from 
     (select 
      * 
     from 
      table1, 
      table2 
     where 
      table1.id = table2.foreign_key_id) sub_query 
    where 
     sub_query.some_field = "some condition" 

享受!

0

正如ck提到的,這真的是基本的sql。

每個$行table1中

SELECT table1.* FROM table1 

發現在表2中的所有行對應於$以$ row.id ==表2排。foreign_id

LEFT JOIN table2 ON table1.id = table2.foreign_id 

如果$行中的所有行符合一定條件

WHERE condition_here 

整個SQL變得

SELECT 
    table1.* 
FROM table1 
    LEFT JOIN table2 ON table1.id = table2.foreign_id 
WHERE condition_here 
+0

是的,讓我們在提問之前先將提及它的所有答案都記下來。 – simendsjo 2010-06-25 15:38:33

0

這裏是一個可能的解決方案。我使用Oracle,不確定MySQL的語法是否完全正確,但我想你可以處理一個等價的東西。

這樣做的想法是找到table2中所有行滿足所需條件的所有id,然後在table1中查找這些id。

SELECT * 
    FROM table1 
    WHERE id IN (
    SELECT id 
     FROM table2 
     GROUP BY id 
     HAVING COUNT(*) = SUM(CASE WHEN <somecondition> THEN 1 ELSE 0 END) 
)